singleton = new Singleton(); 这段代码并非原子操作(开辟内存空间->类的初始化->引用变量赋值),为了提高性能,程序会进行指令的重排序如(开辟内存空间->引用变量赋值->类的初始化),多线程环境下会存在线程拿到未实例完成的类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class Singleton { private volatile static Singleton singleton; private Singleton() { } public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
volatile禁止指令重排序
静态内部类
1 2 3 4 5 6 7 8 9
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
Mac:src mac$ javac -encoding utf-8 Singleton.java Mac:src mac$ javap -c Singleton.class Compiled from "Singleton.java" public final class Singleton extends java.lang.Enum<Singleton> { public static final Singleton INSTANCE;
java.lang.Object object;
public static Singleton[] values(); Code: 0: getstatic #1 // Field $VALUES:[LSingleton; 3: invokevirtual #2 // Method "[LSingleton;".clone:()Ljava/lang/Object; 6: checkcast #3 // class "[LSingleton;" 9: areturn
public static Singleton valueOf(java.lang.String); Code: 0: ldc #4 // class Singleton 2: aload_0 3: invokestatic #5 // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum; 6: checkcast #4 // class Singleton 9: areturn
public java.lang.Object getInstance(); Code: 0: aload_0 1: getfield #9 // Field object:Ljava/lang/Object; 4: areturn
static {}; Code: 0: new #4 // class Singleton 3: dup 4: ldc #10 // String INSTANCE 6: iconst_0 7: invokespecial #11 // Method "<init>":(Ljava/lang/String;I)V 10: putstatic #12 // Field INSTANCE:LSingleton; 13: iconst_1 14: anewarray #4 // class Singleton 17: dup 18: iconst_0 19: getstatic #12 // Field INSTANCE:LSingleton; 22: aastore 23: putstatic #1 // Field $VALUES:[LSingleton; 26: return }
public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable