0

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.

Community
  • 1
  • 1
Sergio
  • 8,532
  • 11
  • 52
  • 94
  • Similar question : http://stackoverflow.com/questions/15156840/singleton-class-with-several-different-classloaders?rq=1 – Pierre Henry Apr 12 '13 at 15:51
  • As to an more lightweight alternative so a stateful EJB : singleton-scoped Spring managed bean. You don't need a JEE app container. It is still a framework to add to your app tough. – Pierre Henry Apr 12 '13 at 15:53
  • The best way to make sure that a single instance exists is to make sure your code only instantiates one instance of the class. You don't need to mix the "protect against multiple instantiations" logic in the class itself - just only call `new Foo()` once in your code! – matt b Apr 12 '13 at 15:57
  • Hi @Pierre Henry, so the first link seems to be only an option if I can control the classloaders. About the second comment, I have not used Spring managed beans before, do you mean that I can use them as a library without having to deploy the application in a EJB like server ?. Otherwise, if I would be changing a EJB container for a Spring one I do not see how that could be useful. Thanks!. – Sergio Apr 12 '13 at 15:58

0 Answers0