1

I'm trying to implement Singleton pattern for the below class. I should have only single instance of class SingletonClass at anytime in the JVM.

Does below code satisfy the Singleton pattern? please provide your suggestions.

public class SingletonClass {

    private static SingletonClass cache = null;
    private static final Object LOCK = new Object();


    // creates one single instance of the class
    public static SingletonClass getInstance() {
        if (cache == null) {
            synchronized (LOCK) {
                if (cache == null) {
                    cache = new SingletonClass();
                }
            }
        }

        return cache;
    }

    public static void main(String[] args) {

        SingletonClass.getInstance();
    }
}
ulab
  • 1,079
  • 3
  • 15
  • 45
  • 1
    Possible duplicate of [What is an efficient way to implement a singleton pattern in Java?](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java) – Kai Mar 14 '16 at 11:28
  • @Kai I did check the questions on singleton. My question is that above code follows the pattern or not. Not how to implement one. I dont see its a duplicate for your downvote. – ulab Mar 14 '16 at 11:30
  • 1
    Then it is offtopic as well. – Sнаđошƒаӽ Mar 14 '16 at 11:31
  • For the downvoters, show if the above code is in the linked duplicates. show some effort to read complete question. – ulab Mar 14 '16 at 11:38

1 Answers1

2

There is a nice article about different approaches of implementing a singleton pattern including your way: Reg's Tech article about Singleton

As mentioned in the article you should (if you want the pattern to be 100% thread safe) also declare the SingletonClass field as volatile. Also you do not need the Object as a lock. Just use synchronized(SingletonClass.class)

Andreas Brunnet
  • 722
  • 6
  • 19
  • Thanks. yes the one difference is on synchronization subject. Is there a downside if I use `Object` as lock in Singleton ? – ulab Mar 14 '16 at 13:13
  • 2
    The only downside I encountered is that you're having an extra field in your class. But I have to say that the way of using a private static final Object as a lock might have the benefit of having a lock that is just accessable within your class. One could use SingletonClass.class outside your actual class as a lock. – Andreas Brunnet Mar 15 '16 at 17:20