Skip to content

Instantly share code, notes, and snippets.

@ixiyang
Created June 17, 2014 03:00
Show Gist options
  • Save ixiyang/860070d1846feeaad20a to your computer and use it in GitHub Desktop.
Save ixiyang/860070d1846feeaad20a to your computer and use it in GitHub Desktop.
Singleton pattern example
/**
*
* thread-safe
*
*/
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
/**
*
* lazy init non-thread-safe
*
*/
public class Singleton {
private static Singleton sInstance;
private Singleton() {
}
public static Singleton getInstance() {
if (sInstance == null) {
sInstance = new Singleton();
}
return sInstance;
}
}
/**
*
* lazy init thread-safe low performance
*
*/
public class Singleton {
private static Singleton sInstance;
private Singleton() {
}
public synchronized static Singleton getInstance() {
if (sInstance == null) {
sInstance = new Singleton();
}
return sInstance;
}
}
/**
*
* lazy init & thread-safe (Java 5 or later)
*
*/
public class Singleton {
private volatile static Singleton sInstance;
private Singleton() {
}
public static Singleton getInstance() {
if (sInstance == null) {
synchronized (Singleton.class) {
if (sInstance == null) {
sInstance = new Singleton();
}
}
}
return sInstance;
}
}
/**
*
* lazy init & thread-safe (for all Java version)
*
*/
public class Singleton {
private Singleton() {
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment