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(); } }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With