Wednesday, June 14, 2006
Thread-safe Memory-friendly Singleton Pattern (Java)
Based on Effective Java (Item 48 - instance on demand holder)
public class MySingleton{
/**
* Private constructor as part of the singleton pattern.
*/
private MySingleton() {
}
/**
* Singleton factory method.
*
* @return the one and only MySingleton.
*/
public static MySingleton getInstance() {
return MySingletonSingletonHolder.theInstance;
}
/**
* Singleton implementation helper.
*/
private static class MySingletonHolder {
static final MySingleton theInstance = new MySingleton();
}
}