1

I have an application that uses JBoss Cache to cache some internal objects and the cache data is persisted in a MySQL database. When the application starts, data persisted in the database will be loaded into the cache. Java serialization mechanism is used to persist the data. I assigned a fixed value to serialVersionUID field for those persistent Java classes.

The problem is that when someone introduces incompatible changes to the serialization format, then the cache data loading from database will fail due to de-serialization errors. After some researches, I got some possible solutions, but not sure which one is the best.

  1. Change the serialVersionUID to use a new version. This approach seems to be easy. But do I need to change all the classes' serialVersionUID field value to the new version, or just the actually changed classes? Because what's been read is actually an object graph, if different serialization versions are used for different classes, will that be a problem when de-serializing the whole object graph?
  2. Use the same serialVersionUID value but create my own readObject and 'writeObject`.
  3. Use Externalizable interface.

Which approach may be the best solution?

Fu Cheng
  • 3,385
  • 1
  • 21
  • 24

1 Answers1

0

The first option is good enough for a cache system as an incompatible serialization change should be a rare event and should be treated as a cache miss. Basically you need to discard from cache the incompatible class instances and re-add the new ones. No need to change the serialVersionUID for compatible classes.

If you want to further minimize the number of incompatibilities between serializable class versions you might consider the second option to customize your class serialization form or provide a serialization proxy. Here you should think if a logical representation of the class is simpler than the default physical representation that might serialize unnecessary implementation details.

Providing a custom serialization form might have further important advantages for a cache system: the size of the serialization form might be reduced and the speed of serialization process might be increased.

See also "Effective Java" by Joshua Block that has a good chapter discussing serialization issues.

Community
  • 1
  • 1
dcernahoschi
  • 14,968
  • 5
  • 37
  • 59