来源:http://melin.iteye.com/blog/838258
三种Singleton的实现方式,一种是用大家熟悉的DCL,另外两种使用cas特性来实现。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
LazySingleton {
private
static
volatile
LazySingleton instance;
public
static
LazySingleton getInstantce() {
if
(instance ==
null
) {
synchronized
(LazySingleton.
class
) {
if
(instance ==
null
) {
instance =
new
LazySingleton();
}
}
}
return
instance;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/**
* 利用putIfAbsent线程安全操作,实现单例模式
*
* @author Administrator
*
*/
public
class
ConcurrentSingleton {
private
static
final
ConcurrentMap<String, ConcurrentSingleton> map =
new
ConcurrentHashMap<String, ConcurrentSingleton>();
private
static
volatile
ConcurrentSingleton instance;
public
static
ConcurrentSingleton getInstance() {
if
(instance ==
null
) {
instance = map.putIfAbsent(
"INSTANCE"
,
new
ConcurrentSingleton());
}
return
instance;
}
}
|
本文转自夏雪冬日博客园博客,原文链接:XXXXXX,如需转载请自行联系原作者
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public
class
AtomicBooleanSingleton {
private
static
AtomicBoolean initialized =
new
AtomicBoolean(
false
);
private
static
volatile
AtomicBooleanSingleton instance;
public
static
AtomicBooleanSingleton getInstantce() {
checkInitialized();
return
instance;
}
private
static
void
checkInitialized() {
if
(instance ==
null
&& initialized.compareAndSet(
false
,
true
)) {
instance =
new
AtomicBooleanSingleton();
}
}
}
|
|
本文转自夏雪冬日博客园博客,原文链接:http://www.cnblogs.com/heyonggang/p/6104677.html,如需转载请自行联系原作者 |