不安全的延时初始化:
/**
* Unsafe lazy initialization
*/
@NotThreadSafe
public class UnsafeLazyInitialization {
private static Resource resource;
//resource的赋值可能和Resource()域的赋值 顺序重排序
public static Resource getInstance() {
if (resource == null)
resource = new Resource(); // unsafe publication
return resource;
}
static class Resource {
}
}
线程not-safe说明:
![](https://images2015.cnblogs.com/blog/731047/201606/731047-20160602133455211-1798703319.png)
安全的延时初始化
/**
* Thread-safe lazy initialization
*/
@ThreadSafe
public class SafeLazyInitialization {
private static Resource resource;
public synchronized static Resource getInstance() {
if (resource == null)
resource = new Resource();
return resource;
}
static class Resource {
}
}
安全的延时初始化
延时初始化占位符模式--使用static初始化--不需要显示的同步
/**
* Lazy initialization holder class idiom
*/
@ThreadSafe
public class ResourceFactory {
private static class ResourceHolder {
//使用static静态初始化(关键)
public static Resource resource = new Resource();
}
//当任何一个线程在首次调用getResource()时,都会使ResourceHolder被加载和被初始化
public static Resource getResource() {
return ResourceFactory.ResourceHolder.resource;
}
}
转载请标明出处:http://www.cnblogs.com/ssslinppp/