0

I have encountered two patterns to make a singleton class

  1. Holder class

    public class Singleton {
        private static final class Holder {
           private static final Singleton INSTANCE = new Singleton();
        }
    
        public static Singleton obtain() {
            return Holder.INSTANCE;
        }
    }
    
  2. Instance variable class

    public class Singleton {
        private static volatile Singleton sInstance;
    
        public static Singleton getInstance() {
            if (sInstance == null) {
            synchronized (LOCK) {
                if (sInstance == null) {
                    sInstance = new Singleton();
                }
            }
           return sInstance;
        }
    }
    

    What is the differnce beetwen the two in regards to performance and best-practices?

6

So the goal of both these patterns is to ensure that the singleton instance is not created until its called. Whilst also making sure it's only ever created once.

In the holder class design, the JVM will only create the static variable the first time the Holder class is used. Putting it in the Holder rather than Singleton avoids the variable being created as soon as the program loads

https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom

In the Second example, the same effect is achieved, but this time by putting the initialisation in the function and ensuring it only runs once with a lock.

Given that you are almost always going to initialise a singleton when your program runs I don't think either of these 'lazy' patterns give you a performance advantage.

Where they might become useful is where you have to control the order of initialisation, or need to provide some user input before initialising

5

Regarding best practices, I don't like singletons. I think they are always a bad idea. You shouldn't care about the difference between the two solutions because they are both singletons.

Regarding performance, if accessing singletons is ever a performance issue, your code is doing something very weird.

So in reality it doesn't really matter.

That said, if you absolutely do have to use a singleton, which of the two solutions you choose is really a matter of personal taste. Do you prefer the more complex code of the double-checked locking pattern in solution 2, or do you prefer the simple code of solution 1 whose thread-safety and efficiency relies on the subtleties of the Java class loading rules?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.