简体   繁体   中英

How to get ride of Null check in singleton design pattern in Java for better performance

To ensure only one instance of the class get created in a multi-threaded environment, we create a singleton class with the below structure.

class Singleton {

    private volatile static Singleton _instance;

    private Singleton() {
        // preventing Singleton object instantiation from outside
    }

    public static Singleton getInstanceDC() {
        if (_instance == null) {
            synchronized (Singleton.class) {
                if (_instance == null) {
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
    }
}

But is there a way we can improve the performance of the class by getting ride of the penalty that every thread has to pay while doing a null check before getting the object from the static function ?

This is known as premature optimization. You don't actually know that the null check is causing a problem (it's not, trust me). The cost of a null check is on the order of nanoseconds.

Worry about performance only after you identify that there actually is a real problem. Then, do some profiling to identify the sections of code that are causing the problem, do not optimize things that "look" like they might be a problem without performance statistics to back up that perception.

According to Josh Bloch. Effective Java Second Edition since Java 1.5 this is the best approach

public enum Singelton {
  INSTANCE;
}

It is safe even against sophisticated serialisation or reflection attacks.

But always keep in mind that Singletons defend testatibility. While the Singleton in your question can be reset for test purposes using reflection, the one in my answer probably cannot.

So I recommend to think twice whether a Singleton is needed, I always avoid them.

The best approach for a Singleton is to instantiate early unless there is some reason for resource constraints.

public class Singleton
{
   //guaranteed thread safe
   private static final Singleton _instance = new Singleton();

   public static Singlegon getInstance()
   {
      return _instance;
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM