Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way by which I can save the state of `static members`?

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?

like image 439
Bhushan Avatar asked Feb 02 '23 16:02

Bhushan


1 Answers

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 shutdown
  • use a static {..} block to load it on next open

The 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.

like image 140
Bozho Avatar answered Feb 05 '23 04:02

Bozho