1. 错误的写法:虽然用到了volatile,但是volatile只能保证可见性,并不保证原子性
public class wrongsingleton {
private static volatile wrongsingleton _instance = null;
private wrongsingleton() {}
public static wrongsingleton getInstance() {
if (_instance == null) {
_instance = new wrongsingleton();
}
return _instance;
}
}
2. 正确写法
public class SafeLazyInitialization {
private static Resource resource;
public synchronized static Resource getInstance() {
if (resource == null)
resource = new Resource();
return resource;
}
}
当然,写法很多,还有其它写法
另外一种写法:
@ThreadSafe
public class EagerInitialization {
private static Resource resource = new Resource();
public static Resource getResource() { return resource; }
}
延迟初始化的写法:
@ThreadSafe
public class ResourceFactory {
private static class ResourceHolder {
public static Resource resource = new Resource();
}
public static Resource getResource() {
return ResourceHolder.resource ;
}
}