线程安全的单例模式写法
1
2
3
4
5
6
7
8
9
|
@ThreadSafe
public class SafeLazyInitialization {
private static Resource resource;
public synchronized static Resource getInstance() {
if (resource == null )
resource = new Resource();
return resource;
}
}
|
另外一种写法:
1
2
3
4
5
|
@ThreadSafe
public class EagerInitialization {
private static Resource resource = new Resource();
public static Resource getResource() { return resource; }
}
|
延迟初始化的写法:
1
2
3
4
5
6
7
8
9
|
@ThreadSafe
public class ResourceFactory {
private static class ResourceHolder {
public static Resource resource = new Resource();
}
public static Resource getResource() {
return ResourceHolder.resource ;
}
}
|
二次检查锁定/Double Checked Locking的写法(反模式)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class SingletonDemo {
private static volatile SingletonDemo instance = null ; //注意需要volatile
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null ) { //二次检查,比直接用独占锁效率高
synchronized (SingletonDemo . class ){
if (instance == null ) {
instance = new SingletonDemo ();
}
}
}
return instance;
}
}
|
本文作者:StanWind
文章标题: 线程安全的单例模式写法
本文地址:https://www.stanwind.com/post/67
版权声明:若无注明,本文皆为“Make it Better”原创,转载请保留文章出处。
本文地址:https://www.stanwind.com/post/67
版权声明:若无注明,本文皆为“Make it Better”原创,转载请保留文章出处。
相关文章