Java – How Isolated Are Static Variables in JVM?

javajvmstatic

If I have a

public class SomeClass {
    public static final HashMap hashmap = new HashMap();
}

and then I have five different classes with main(String[] args) methods, that I will run.

when they access SomeClass.hashmap, would they be accessing the same HashMap or will they each have their own hashmap created in the JVM?

Best Answer

The answer is "each instance of the class within a different class loader is distinct."

If you have two different JVMs (you invoked java MainOne and java MainTwo), these are obviously different class loaders. However, there are corner cases here with things such as nailgun which keeps the JVM running and... things get complex.

You also have situations such as when the application is launched from within an IDE. Some IDEs will spawn a new JVM for running the application, others could be launching a new class loader within their own JVM (I don't think any do this anymore as it made the IDE less than ideally stable). This can get very tricky too.

When running in within an application server environment, this can either be configurable, or you will need to check the specifications. However, realize that every possible combination is possible. You can have isolation of two modules within the same ear (each .war has its own class loader), you can the entire .ear share a class loader, you can have some funky compatibility mode where everything shares the .jar class loader, but is itself in an isolated class loader for the .war, or you can have the entire server use one class loader. Note that some application servers have changed how they work with different versions (JBoss prior to version 5 was not isolated, while after version 5 was, and 4.0.2 had a hierarchal class loader while 4.0.3 reverted to a unified class loader). It's a mess. And thus the awareness of "static is one per class loader" is key.

It is even possible to have different class loaders within a single application as demonstrated in run a executable jar file within java program using class loaders.

So, going back to the answer "each instance of the class within a different class loader is distinct" - and that can take many different forms and edge conditions.