单例实现方式一, 锁机制
- 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(), 会产出堆内存浪费.
来源: http://www.bubuko.com/infodetail-2970650.html