CAS是项乐观锁技术,当多个线程尝试应用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,失败的线程并不会被挂起,而是被告知这次竞争中失败,并能够再次尝试。实现单例的形式如下:
import java.util.concurrent.atomic.AtomicReference;/** * 应用CAS保障线程平安 * @author shixiangcheng * 2019-12-20 */public class Singleton { private static final AtomicReference<Singleton> INSTANCE=new AtomicReference<Singleton>(); private Singleton(){} public static Singleton getInstance(){ for(;;){ Singleton singleton=INSTANCE.get(); if(singleton!=null){ return singleton; } singleton=new Singleton(); if(INSTANCE.compareAndSet(null, singleton)){ return singleton; } } }}
用CAS的益处在于不须要应用传统的锁机制来保障线程平安,CAS是一种基于忙期待的算法,依赖底层硬件的实现,绝对于锁它没有线程切换和阻塞的额定耗费,能够反对较大的并行度。
CAS的一个重要毛病在于如果忙期待始终执行不胜利(始终在死循环中),会对CPU造成较大的执行开销。
另外,如果N个线程同时执行到singleton = new Singleton();的时候,会有大量对象创立,很可能导致内存溢出。