很多时候我们并不需要一个类创建的对象是全局唯一的,只需要保证在单个线程内是唯一的、线程安全的就可以。为了实现单线程内部的单例,我们可以用ThreadLocal或CAS实现。
利用ThreadLocal实现
先看代码:
public class ThreadLocalSingleton {
private static final ThreadLocal<ThreadLocalSingleton> instance = new ThreadLocal<ThreadLocalSingleton>(){
@Override
protected ThreadLocalSingleton initialValue(){
return new ThreadLocalSingleton();
}
};
private ThreadLocalSingleton(){}
public static ThreadLocalSingleton getInstance(){
return instance.get();
}
}
利用ThreadLocal可以实现单线程内部的单例模式
利用CAS实现
先看代码:
public class CASSingleton {
private static final AtomicReference<CASSingleton> INSTANCE = new AtomicReference<CASSingleton>();
private static CASSingleton instance;
private CASSingleton(){}
public static final CASSingleton getInstance(){
for(;;){
instance = INSTANCE.get();
if(null != instance){
return instance;
}
INSTANCE.compareAndSet(null,new CASSingleton());
return INSTANCE.get();
}
}
}
利用CAS可以实现单线程内部的单例模式
标签:CASSingleton,模式,instance,ThreadLocal,static,private,单例,设计模式 From: https://blog.51cto.com/dongfeng9ge/9116547