What are the issues with non-static inner classes and serialization in Java

java, performance, serialization

Solution

An inner class holds a reference to its outer class, so attempting to serialize the inner will also serialize the outer -- as well as any other objects that the outer might hold. This could result in a huge object graph. Or it could fail, if the outer has state that can't be serialized (such as an InputStream object).

That said, there are times when you have to make inner classes Serializable, even if you never plan to serialize them. For example, if you're working with Swing.

If you do plan to serialize these objects, I'd question why they'd need to be inner classes irrespective of performance. Generally, you're only going to serialize data containers, and such containers rarely (if ever) need a reference to some "parent" class. Consider making these objects nested (static) classes rather than inner classes.

Problem

This morning my boss and I had a long and ultimately fruitless discussion about this, in the context of trying to diagnose performance problems with a web application. We didn't really come to any conclusions. I think we're right in thinking that Serializable non-static inner classes have issues, but we're not sure precisely what the issues are or what exactly to avoid (we reasoned that we couldn't always simply avoid it). Can anyone suggest any guidelines for not getting in trouble with this issue?

Original source