写在最前
常见的实现单例模式有很多种,我就不多说了。下面也是一种思路,可以用来替换常用的Double Check方式来实现安全的单例模式。
package com.hello.is.test;
import java.util.concurrent.atomic.AtomicReference;
/**
* 更加优美的Singleton, 线程安全的
*
* @author andy
*
*/
public class Singleton {
/** 利用AtomicReference */
private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>();
/**
* 私有化
*/
private Singleton(){
}
/**
* 用CAS确保线程安全
*
* @return
*/
public static final Singleton getInstance(){
for (;;) {
Singleton current = INSTANCE.get();
if (current != null) {
return current;
}
current = new Singleton();
if (INSTANCE.compareAndSet(null, current)) {
return current;
}
}
}
/**
* 测试case
*
* @param args
*/
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2);
}
}