Search code examples
javaglobal-variablesclassloader

Truly global state in Java, "more global" than `static`?


I am looking for a way to maintain a truly global variable in Java, one that is valid for the entire JVM instance.

If I simply used a static field somewhere, it will fail if the class containing the field is loaded multiple times by different classloaders.

I can think of some nasty ways to resolve this, such as using only JDK standard classes (which should normally be loaded by the same classloader always), or asking a custom MBean to keep the global state, but these seem like hacks to me.

Disclaimer: I know that global state is bad, and yes, I avoid it whenever I can. Promise.


Solution

  • If your problem is related to multiple classloaders, then you need the global object to be loaded by the system classloader, or other shared classloader.

    How that is setup depends on how you run your app, e.g. in Tomcat, any jar file in the CATALINA_BASE/lib folder is added to the shared classloader.

    Once you class is loaded by the correct classloader, static fields will work the way you want them to.