Skip to content

Instantly share code, notes, and snippets.

@KodeSeeker
Created September 7, 2014 02:43
Show Gist options
  • Save KodeSeeker/c342915cacc9b984a08d to your computer and use it in GitHub Desktop.
Save KodeSeeker/c342915cacc9b984a08d to your computer and use it in GitHub Desktop.
SimpleSingleton
public class Singleton
{
private Singleton singleton;
//make the constructor protected- to defeat instantiation.
protected Singleton(){}
public static Singleton getInstance() {
if(singleton == null) {
singleton = new ClassicSingleton();
}
return singleton;
}
@kush2207
Copy link

kush2207 commented Oct 9, 2015

This is not thread-safe though. Once you have public static method/property, there's always danger of thread-safety. You need to guard your null check/construction on the singleton member instance. you can do something like this:

public static Singleton getInstance() {
      if(singleton == null) {
         try {
               singletonLock.lock(); //define singletonLock as a member field in Singleton class

               //need to check for null again (double-checked locking //ref:https://en.wikipedia.org/wiki/Double-checked_locking)
               if(singleton == null) {
                    singleton = new ClassicSingleton();
               }
          }
          finally {
               singletonLock.unlock();
          }
      }
      return singleton;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment