Double-checked lock singleton mode

  1. DCL singleton is a thread-safe, lazy loading, efficient singleton implementation method
  2. The first test is much more efficient because no thread passes the first test until the object is successfully initialized, while the second test ensures that the instance is initialized only once.
  3. If volatile does not modify the singleton, instruction reordering can occur, leading to errors. Instantiate the object, divided into 3 steps, allocate space -> initialize the object -> point the object to the allocated space, if the second and third steps are rearranged, an exception will occur.
Public class Singleton {/** Singleton */ private static volatile Singleton instance; Private Singleton() {} public static Singleton getInstance() {if (instance == null) {// if (instance == null) synchronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}Copy the code