Search code examples
javacachingserializationaerospike

If i changed the package of a java class. Will the deserialization from the old serialized version still work?


I am using aerospike as cache in my java project. I changed the package of one of my cached objects. I have deployed new code on one machine. Getting serialize exception as old cached objects are there in the cache.

I want old code to run on some machines and new on some and both should be able to get/put objects in the aerospike cache.

Is there a way to achieve this? Why exactly am i getting this exception.


Solution

  • The package to which a class belongs is a fundamental part of that class's identity, as reflected by the package name being part of the class's fully-qualified name. For all practical intents and purposes, changing the package to which a class is assigned drops the original class and replaces it with a completely different class.

    In particular, if you serialize an instance of a class named "my.package.MyClass" via Java serialization, then successfully deserializing the result always yields an instance of a class named "my.package.MyClass". If no such class can be loaded, or if the serialization version of the one that is loaded does not match that of the one that was serialized, then deserialization will fail.

    If you retain the old class along with the new class then you can perhaps patch up the deserialization problem in the new version of the application. Simply be prepared for objects of the old class, and convert them to instances of the new class as soon as you deserialize them. But if you want the new version of the application to play well with the old, then you must also do the reverse when the new one serializes objects of the affected class, else you will just cause the old application to have deserialization errors. At this point, you should be considering whether changing the package name was all that important after all.

    Overall, Java serialization is not well suited for object storage. It is primarily targeted at object communication. You might consider switching to an XML-, JSON-, or YAML-based serialization format, which at least you could twiddle between cache and consumer. Such a change would of course be incompatible with the old version of your application, but so, apparently, is the package change you have already performed.