Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Safe Efficient way to implement singleton pattern in Java? [duplicate]

Possible Duplicate:
Efficient way to implement singleton pattern in Java

I was reading this Best Singleton Implementation In Java, but its not thread safe.

As per wiki :

if(singleton==null) { synchronized(Singleton.class) { // this is needed if two threads are waiting at the monitor at the // time when singleton was getting instantiated if(singleton==null) singleton= new Singleton(); }
}

But Find Bugs utility gives two errors in this : 1. Double null check. 2. Incorrect lazy initialization of static field.

What is the best way,

Is it Correct :

synchronized (Singleton.class) {
if (singleton== null) {
singleton= new Singleton();
}
}
like image 438
Pradeep Avatar asked Dec 19 '10 10:12

Pradeep


People also ask

What is an efficient way to implement a singleton pattern in Java?

The most popular approach is to implement a Singleton by creating a regular class and making sure it has: A private constructor. A static field containing its only instance. A static factory method for obtaining the instance.

How can we make Singleton pattern thread safe in Java?

Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.

How singleton implementation can be made thread safe?

Thread Safe Singleton: A thread safe singleton is created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread safe, getInstance() method is made synchronized so that multiple threads can't access it simultaneously.

How can we avoid cloning in case of singleton implementation?

Prevent Singleton Pattern From Cloning To overcome the above issue, we need to implement/override the clone() method and throw an exception CloneNotSupportedException from the clone method. If anyone tries to create a clone object of Singleton , it will throw an exception, as shown in the below code.


1 Answers

The most efficient/simplest way to make a lazy loading Singleton is just

enum Singleton {
   INSTANCE
}

Note: there is no need for locking as class loading is thread safe. The class is final by default and the constructor cannot be called via reflection. The INSTANCE will not be created until the INSTANCE, or the class is used. If you are worried the class might be accidentally used you can wrap the singleton in an inner class.

final class Singleton {
    private Singleton() { }
    static class SingletonHolder {
        static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

IMHO, you have to be pretty paranoid to consider this a better solution.

like image 134
Peter Lawrey Avatar answered Oct 20 '22 00:10

Peter Lawrey