不使用synchronized和lock 锁实现线程安全单例

单例实现方式一,锁机制

public class Singleton {
private static Singleton singleton=null; public Singleton() {
}
public static Singleton getIntance(){
if(singleton==null){
synchronized (Singleton.class){
if(singleton==null){
singleton=new Singleton();
}
}
}
return singleton;
}
}
单例实现方式二,静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton singleton = new Singleton(); } public Singleton() {
} public static Singleton getIntance() {
return SingletonHolder.singleton;
}
}
静态内部类虽然没有显示调用synchronized,但是借助ClassLoad的线程安全机制,隐式调用了synchronized
单例实现方式三,CAS操作
public class Singleton {
private static final AtomicReference<Singleton> instance = new AtomicReference<>(); public Singleton() {
} public static Singleton getIntance() {
for (; ; ) {
Singleton singleton = instance.get();
if (singleton == null) {
singleton = new Singleton();
instance.compareAndSet(null, singleton);
}
return singleton;
}
} public static class SingletonHold implements Runnable { @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + Singleton.getIntance());
} } public static void main(String[] args) {
SingletonHold singletonHold = new SingletonHold();
Thread thread1 = new Thread(singletonHold);
Thread thread2 = new Thread(singletonHold);
Thread thread3 = new Thread(singletonHold);
thread1.start();
thread2.start();
thread3.start();
}
}
运行结果:

Thread-0:com.rongke.web.Singleton@7249381e
Thread-1:com.rongke.web.Singleton@7249381e
Thread-2:com.rongke.web.Singleton@7249381e

使用cas好处:不需要使用锁来实现线程安全,而是依赖底层硬件实现,减少了因为锁导致线程切换和阻塞的性能开销,可以支持较大的并行度

使用cas缺点:如果线程一直处于for无限循环中,对cpu性能影响很大,如果多个线程执行singleton=new Singleton(),会产出堆内存浪费。

上一篇:Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数


下一篇:无锁,线程安全,延迟加载的单例实现(C#)