There is no need to deal with Unsafe for this. If you use a reflection
Field, while ugly, it *does* publish writes to a final field with volatile
semantics internally. I would argue that using a ThreadLocal in this
fashion would be far uglier.
There is another alternative. Use writeReplace
Stephen Colebourne wrote:
Workarounds include lazily creating the caches in transient fields,
bloating the serialzed data, using reflection or creating a dummy inner
class to act as the serialized form. All are rubbish solutions.
IMO, a "serial proxy" is a good rubbish solution. Nested classe
Thanks for the info. Unfortunately, JSR-310 cannot use unsafe, as it
needs to be usable outside the JDK.
For info, I compared the sizes of a neatly trimmed output (using a
Serialization proxy class) with the best achievable without one. 277
bytes without, 99 bytes with a proxy. So, this isn't an e
It's sad to see this issue of serialization vs. final resurface so many
times. I have complained about this myself a number of times. The 'final'
modifier is counter-intuitive as it doesn't really prohibit modification
(most developers don't know that even a 'private static final' field can be
upda
Stephen Colebourne wrote:
I thought I'd raise an issue with serialization that I've had a
problem with more than once. Perhaps there is an obvious easy
solution, but I can't see it (I can see hard workarounds...)
In JSR-310 we have lots of immutable classes. One of these stores four
fields:
Agreed, the solution below works in the use case I gave (and thats
what I'm using as a workaround). However, its not optimal, which is
why I raised the (broader) question here.
(This solution doesn't allow me to use readObject/writeObject to
actually control the wire bits, such as to flatten the D
I would put the first element to a different field, make periods field
transient and implement a readResolve method that calls a constructor.
So, something like this should solve your problem easily, right?
private final String name
private final Duration duration
private final PeriodField fir