Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it optimal to use the double checked locking idiom for the singleton pattern?

Is it better to use the double checked locking idiom for a singleton pattern? Or a synchronised method?

ie:

private static volatile ProcessManager singleton = null;

public static ProcessManager getInstance() throws Exception {

    if (singleton == null) {
       synchronized (MyClass.class) {
          if (singleton == null) {
               singleton = new ProcessManager();
         }
      }
   }
   return singleton;

}

or

private static processManager singleton = null;

public synchronized static processManager getInsatnce() throws Exception {

   if(singleton == null) {
            singleton = new processManager();
    }

    return singleton
 }
like image 954
Pectus Excavatum Avatar asked Mar 20 '13 14:03

Pectus Excavatum


1 Answers

Have the ClassLoader do the job for you :

    /*
     * This solution takes advantage of the Java memory model's guarantees about class initialization
     * to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it
     * is needed. That means that the first time getInstance is called, mySingletonServiceLoader
     * will be loaded and instance will be created, and since this is controlled by ClassLoaders,
     * no additional synchronization is necessary.
     */
    public static DocumentService getInstance() {
        return mySingletonServiceLoader.INSTANCE;
    }

    private static class mySingletonServiceLoader {
         static DocumentService INSTANCE = new DocumentService();
    }
}
like image 100
LaGrandMere Avatar answered Sep 30 '22 14:09

LaGrandMere