* 1st version: creates multiple instance if two thread access
* this method simultaneously
*/publicstaticSingletongetInstance() {
if (_instance ==null) {
_instance =newSingleton();
}
return _instance;
}
/**
* 线程安全
* 2nd version : this definitely thread-safe and only
* creates one instance of Singleton on concurrent environment
* but unnecessarily expensive due to cost of synchronization
* at every call.
*/publicstaticsynchronizedSingletongetInstanceTS() {
if (_instance ==null) {
_instance =newSingleton();
}
return _instance;
}
/**
* 双锁校验
* 3rd version : An implementation of double checked locking of Singleton.
* Intention is to minimize cost of synchronization and improve performance,
* by only locking critical section of code, the code which creates
instance of Singleton class.
* By the way this is still broken, if we don't make _instance volatile,
as another thread can
* see a half initialized instance of Singleton.
*/publicstaticSingletongetInstanceDC() {
if (_instance ==null) {
synchronized (Singleton.class) {
if (_instance ==null) {
_instance =newSingleton();
}
}
}
return _instance;
}
}
2. Enum实现方式(推荐)
/** * Singleton pattern example using Java Enumj */