寫一個執行緒安全的單例模式
阿新 • • 發佈:2019-02-14
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 ;
}
}