Just like the way we save the instance variables
using serialization, is there any way by which I can save the state of static
members?
If there is a situation, where getting back the state of static members is necessary to restore something, how would one do that?
The easiest option that comes to my mind is to use a singleton rather than static fields. The singleton object can be serialized and deserialized, and you can manage its lifetime, while you preserve the 'global state' that static fields give you (that said, global state is a bad thing, but that's a different topic)
Otherwise - the static state is preserved throughout the lifetime of the classloader (which usually means the lifetime of the JVM). So if you want to persist state, it makes sense to do it on shutdown, and restore it on class load.
Runtime.addShutdownHook(..)
to perform the serialization on shutdownstatic {..}
block to load it on next openThe serialization format can be anything. JSON, BSON, java serialization (using ObjectOutputStream
)
But this is an unusual and in most cases the wrong thing to do. So make sure this is what you want. If you simply want the state to live for the lifetime of the application, don't do anything. And if you want to persist something for longer, either pick the singleton option or consider using a small database rather than static fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With