62,616
社区成员
发帖
与我相关
我的任务
分享
class Singleton{
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
static {};
Code:
0: new #3 // class Singleton1
3: dup
4: invokespecial #4 // Method "<init>":()V
7: putstatic #2 // Field INSTANCE:LSingleton1;
10: return
new是在static静态代码块中执行的,但这个代码块将会生成<cinit>方法,这正好说明了new是发生在类初始化这一个步骤中的(即<cinit>),但是类初始化这一个步骤的触发唯有靠我最先提到的那几种方式,这里就是通过getstatic静态方法,通过getInstance来触发类初始化,进而new发生了。
public class Singleton1 {
public static Singleton1 getInstance();
Code:
0: getstatic #2 // Field INSTANCE:LSingleton1;
3: areturn
static {};
Code:
0: new #3 // class Singleton1
3: dup
4: invokespecial #4 // Method "<init>":()V
7: putstatic #2 // Field INSTANCE:LSingleton1;
10: return
懒汉模式Singleton2:
public class Singleton2 {
public static synchronized Singleton2 getInstance();
Code:
0: getstatic #2 // Field instance:LSingleton2;
3: ifnonnull 16
6: new #3 // class Singleton2
9: dup
10: invokespecial #4 // Method "<init>":()V
13: putstatic #2 // Field instance:LSingleton2;
16: getstatic #2 // Field instance:LSingleton2;
19: areturn
static {};
Code:
0: aconst_null
1: putstatic #2 // Field instance:LSingleton2;
4: return
}
饿汉模式的new是否在getInstance时再去操作?
public class Singleton1 {
private static Singleton1 INSTANCE = new Singleton1();
private Singleton1() {}
public static Singleton1 getInstance() {
return INSTANCE;
}
}
Eager initialization
public class Singleton2{
private static Singleton2 instance = null;
private Singleton2() { }
public static synchronized Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}
return instance;
}
}
Briefly, how to understand Singleton2 is not a lazy initialization?
In my mind, I think the time of creating the instance between the two examples is the same, all on calling the method getInstance
Ask for consultation,thanks.