分隔
public class SingletonDemo { private static SingletonDemo instance=null; private SingletonDemo(){} public static SingletonDemo getSingle() { if (instance==null) { instance=new SingletonDemo(); } return instance; } }分隔
public class SingletonDemo { private static SingletonDemo instance=null; private SingletonDemo(){ System.out.println("I am constructor"); } public static SingletonDemo getSingle() { if (instance==null) { instance=new SingletonDemo(); } return instance; } public static void main(String[] args) { for (int i=0; i<10; i++) { new Thread(() -> {SingletonDemo.getSingle(); },String.valueOf(i)).start(); } } }
分隔
public class SingletonDemo { private static SingletonDemo instance=null; private SingletonDemo(){ System.out.println("I am constructor"); } public static synchronized SingletonDemo getSingle() { if (instance==null) { instance=new SingletonDemo(); } return instance; } public static void main(String[] args) { for (int i=0; i<10; i++) { new Thread(() -> {SingletonDemo.getSingle(); },String.valueOf(i)).start(); } } }
分隔
DCL(Double Ckeck Lock)双端检锁机制
public static SingletonDemo getSingle() { if (instance==null) { synchronized(SingletonDemo.class) { if (instance==null) { instance=new SingletonDemo(); } } } return instance; }分隔
上面的代码是否一定正确呢?
不一定,指令重排
DCL(双端检索)机制不一定线程安全,
分隔
禁止指令重排
private static volatile SingletonDemo instance=null;