不简单的单例模式

2019-04-14 18:09发布

微软面试,大摩电面的时候都问到了设计模式,首推当然是单例模式了
单例模式其实很简单,不简单的是,如果扯上多线程,该如何加锁。 下面的内容主要是来自维基百科, eager模式: 这种模式就不会存在多线程同步的问题了。 public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }
  • The instance is not constructed until the class is used.
  • There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
  • The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.

lazy模式 双重锁,保证同步。两次判断instance是否为空。且要求instance是volatile,要求编译器不要做优化,每次都从寄存器中读取值,而不是使用cpu cache中的数据。 This method uses double-checked locking, which should not be used prior to J2SE 5.0, as it is vulnerable to subtle bugs. The problem is that an out-of-order write may allow theinstance reference to be returned before the Singleton constructor is executed.[8] public class SingletonDemo { private static volatile SingletonDemo instance = null; private SingletonDemo() { } public static SingletonDemo getInstance() { if (instance == null) { synchronized (SingletonDemo.class) { if (instance == null) { instance = new SingletonDemo(); } } } return instance; } }

另一种方式,降低了并发度,就是将整个方法进行加锁 An alternate simpler and cleaner version may be used at the expense of potentially lower concurrency in a multithreaded environment: public class SingletonDemo { private static SingletonDemo instance = null; private SingletonDemo() { } public static synchronized SingletonDemo getInstance() { if (instance == null) { instance = new SingletonDemo(); } return instance; } }