How to create a real singleton in java?

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.

+5
source share
4 answers

The only way to make your singleton class loaded with a single classloader is to put this jar file in the bootclasspath, for example.

, , . , . , , .

+5

JavaEE , singleton "", .

, JBoss xyz-service.xml, , JNDI JMX, (, EJB) . .

+5

J2EE , , , JVM. , , JNDI . Glassfish . JNDI, JNDI, .

, GlassFish , JNDI, . , JVM, , .

, J2EE , J2EE - . - - , , ( , ), J2EE.

+3

TRUE Singleton, :

  • final.
  • Singleton private static final
  • private constructor public getInstance().
  • , Singleton one ClassLoader only
  • override the method readResolve()and return the same instance without creating a new instance during the de-serialization process.

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?

0
source

All Articles