What are the problems with non-stationary inner classes and serialization in Java

This morning, my boss and I had a long and ultimately fruitless discussion about this, in the context of trying to diagnose performance issues with a web application. We did not come to any conclusions.

I think we are right in thinking that Serializable non-static inner classes have problems, but we don’t know exactly which problems or what should be avoided (we reasoned that we can’t always just avoid this), can anyone to offer any recommendations in order not to get into a problem with this problem?

+6
java performance serialization
source share
4 answers

The inner class contains a reference to its outer class, so an attempt to serialize the inner will also serialize the outer - as well as any other objects that may have external ones. This can lead to a huge graph of objects. Or it may fail if the external state cannot be serialized (for example, an InputStream object).

However, there are times when you need to make Serializable inner classes, even if you never plan to serialize them. For example, if you work with Swing.

If you plan to serialize these objects, I would question why they should be inner classes regardless of performance. Typically, you are going to serialize data containers, and such containers rarely (if ever) need a reference to some kind of "parent" class. Consider making these objects nested (static) classes, not inner classes.

+7
source share

Just realizing that a serialized inner class has an implicit reference to its containing object will go a long way. This link has a number of consequences:

  • The link is generated automatically, so it cannot be transient
  • The outer class must be serializable
  • The outer class will be automatically serialized with the inner class
  • An external object cannot be separated from its internal object

Probably the main rule I can extract is "do not serialize inner classes other than their containing object." I can no longer think about what happened.

+3
source share

Think. If your outer class includes a (non-temporary) collection of instances of the inner class, then every time you serialize one of the instances of the inner class, you actually pull all of them into serialization.

0
source share

You can make the Externalizable class and write your own writeExternal and readExternal methods that send only the fields you need.

http://java.sun.com/javase/6/docs/api/java/io/Externalizable.html

0
source share

All Articles