public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
Compiled from "Singleton.java"
public class Singleton {
public static Singleton getSingleton();
Code:
0: getstatic #2 // Field singleton:LSingleton;
3: ifnonnull 37
6: ldc #3 // class Singleton
8: dup
9: astore_0
10: monitorenter
11: getstatic #2 // Field singleton:LSingleton;
14: ifnonnull 27
17: new #3 // class Singleton
20: dup
21: invokespecial #4 // Method "<init>":()V
24: putstatic #2 // Field singleton:LSingleton;
27: aload_0
28: monitorexit
29: goto 37
32: astore_1
33: aload_0
34: monitorexit
35: aload_1
36: athrow
37: getstatic #2 // Field singleton:LSingleton;
40: areturn
Exception table:
from to target type
11 29 32 any
32 35 32 any
}
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
10: monitorenter
11: getstatic #2 // Field singleton:LSingleton;
14: ifnonnull 27
17: new #3 // class Singleton 创建一个对象,分配内存
20: dup // 复制栈顶数值并将复制值压入栈顶
21: invokespecial #4 // Method "<init>":()V 调用超类构造方法,实例初始化方法,私有方法
24: putstatic #2 // Field singleton:LSingleton; 为指定的类的静态域赋值
27: aload_0 // 将第一个引用类型本地变量推送至栈顶
28: monitorexit
public class Singleton {
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}