In Java, sharing state using static variables can be the cause of problems difficult to debug, in addition to VERY often being a symptom of bad design.
For example, I am aware that the state may not be correctly synchronized in a multi-threaded application, since different threads may have different copies of the static variables in their registers. Furthermore, if the class having the static variable is loaded by more than one classloader, multiple copies of the static variable may exist.
The first problem could be easily solved using the volatile
keyworkd in the static variable declaration (and synchronizing the access to its methods if necessary).
For the second problem, what is the best way to warranty that only a single instance exists and only that instace will be visible in the JVM ?. I found in another post some people recomending to use an enum:
What is an efficient way to implement a singleton pattern in Java?
But I think that would not solve the problem if multiple class loaders are present.
At first sight, I would think in using something like a syngleton stateful EJB for this, but I am wondering if a more ligthweight approach exists.
Finally, are there other technical problems related to sharing state using static variables (besides the two I mentioned above) that I am not aware of ?.
Disclaimer:
This question intentionally excludes a discussion on the bad design that often implies the usage of a static variable in Java for sharing state (since this has been properly discussed in many other places) and is focussed on the technical problems only.