Am 25.07.2017 um 22:52 schrieb rdp:
> Serialization works fine but when I deserialize the transient field in
> null. I want to initialise this field.
>
> This worked perfectly fine when i use default Java Serialization with
> memcached session manager as I added readObject method to my class which
> gets called on deserialization and I initialise the transient field.
>
> But I am unable to do this with Kryo Serialization.
Yes, that's standard behaviour for transient fields: They don't get
serialized or deserialized.
Different frameworks offer different ways to add initialization code,
but this tends to be difficult anyway - during deserialization, fields
may not yet be filled, object graphs may not yet be fully there, so any
code that runs during deserialization is pretty fragile and dependent on
internals of the deserialization framework (such as object
deserialization order).
The best way around this is to design your transient fields to be
initialized on demand. On-demand means that anything that's needed to
populate that fields is already there, or at least subject to on-demand
initialization.
The only thing you have to worry about in this scenario is circular
on-demand initialization dependencies, but at least that's entirely
within your own code and does not involve library code from third parties.
Since Kryo uses the default constructor, you can initialize the
transient field there, that's even easier.
> I decided to implement KryoSerializable as shown below.(Its sample code
> similar to my original class)
>
> My transient field gets initialized by the read method but map1 and
> map2 dont serialise correctly so when deserialization happens map1 and
> map2 are empty.
Yeah, the KryoSerializable Javadoc says you need to implement read() and
write() yourself, but you don't do it so the nontransient fields don't
get (de)serialized.
I don't know the best way to do that though; maybe somebody else can
give a hint.