如图使用CAS创建单例
高并发的获取单例的场景下,cpu消耗会非常大
public class Service {
private Service() {
}
//基于CAS的单例模式
private static final AtomicReference<Service> INSTANCE = new AtomicReference<Service>();
public static final Service getInstance() {
for (; ; ) {
Service current = INSTANCE.get();
if (current != null) {
return current;
}
current = new Service();//高并发的场景下,可能会创建多个对象,但是最终只有一个会被使用,其它的会被丢弃
System.out.println(current);
if (INSTANCE.compareAndSet(null, current)) {
return current;
}
}
}
}
在高并发的初始化单例的场景下,可能会创建多个,但是最终对外提供的单例是同一个!
public static void main(String[] args) throws ClassNotFoundException {
for (int i = 1; i <= 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Service instance = Service.getInstance();
}
}).start();
}
}
//基于CAS的单例模式
private static final AtomicReference<Service> INSTANCE = new AtomicReference<Service>();
public static final Service getInstance() {
for (; ; ) {
Service current = INSTANCE.get();
if (current != null) {
return current;
}
current = new Service();//高并发的场景下,可能会创建多个对象,但是最终只有一个会被使用,其它的会被丢弃
System.out.println(current);
if (INSTANCE.compareAndSet(null, current)) {
return current;
}
}
}
结果——创建了多个对象
image.png
网友评论