Skip to content

Instantly share code, notes, and snippets.

@kevalpatel2106
Created November 29, 2016 10:39
Show Gist options
  • Save kevalpatel2106/b9149d377042bd18bf13acfb94a155d2 to your computer and use it in GitHub Desktop.
Save kevalpatel2106/b9149d377042bd18bf13acfb94a155d2 to your computer and use it in GitHub Desktop.
public class SingletonClass {
private static volatile SingletonClass sSoleInstance;
//private constructor.
private SingletonClass(){
//Prevent form the reflection api.
if (sSoleInstance != null){
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static SingletonClass getInstance() {
//Double check locking pattern
if (sSoleInstance == null) { //Check for the first time
synchronized (SingletonClass.class) { //Check for the second time.
//if there is no instance available... create new one
if (sSoleInstance == null) sSoleInstance = new SingletonClass();
}
}
return sSoleInstance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment