I ran into a problem with my single when used in multiple classloaders. For example, Singleton, accessed by multiple EJBs. Is there a way to create a singleton that has only one instance for all classloaders?
I am looking for a pure Java solution, either using a custom class loader, or some other way.
The only way to make your singleton class loaded with a single classloader is to put this jar file in the bootclasspath, for example.
, , . , . , , .
JavaEE , singleton "", .
, JBoss xyz-service.xml, , JNDI JMX, (, EJB) . .
J2EE , , , JVM. , , JNDI . Glassfish . JNDI, JNDI, .
, GlassFish , JNDI, . , JVM, , .
, J2EE , J2EE - . - - , , ( , ), J2EE.
TRUE Singleton, :
Singleton
final
private static final
private constructor
public getInstance()
one ClassLoader only
readResolve()
Code example:
final class LazySingleton { private LazySingleton() {} public static LazySingleton getInstance() { return LazyHolder.INSTANCE; } private static class LazyHolder { private static final LazySingleton INSTANCE = new LazySingleton(); } private Object readResolve() { return LazyHolder.INSTANCE; } }
See the SE section below for more details:
What is an efficient way to implement a singleton pattern in Java?