对于以下 2 个类,获得相同的 Java 字节码。
java版本:
java 版本“1.8.0_181”Java(TM) SE 运行时环境(构建
1.8.0_181-b13) Java HotSpot(TM) 64 位服务器 VM(内部版本 25.181-b13,混合模式)
javac 和 javap 版本:
1.8.0_181
我的疑问是
不应该使用方法同步的关键字有不同的字节码,如我们所见同步块 has monitorenter
and monitorexit
,或者让我们假设我不应该混合同步块 and 同步的
方法 then
-
JVM 如何以不同的方式处理这两种方法?
public class MySingleton1 {
private MySingleton1() {}
private static MySingleton1 ourInstance;
public static MySingleton1 getInstance() {
if (ourInstance == null) {
ourInstance = new MySingleton1();
}
return ourInstance;
}
}
and
public class MySingleton2 {
private MySingleton2() {}
private static MySingleton2 ourInstance;
public static synchronized MySingleton2 getInstance() {
if (ourInstance == null) {
ourInstance = new MySingleton2();
}
return ourInstance;
}
}
字节码如下:
$javac MySingleton1.java
$javap -c MySingleton1
$javac MySingleton2.java
$javap -c MySingleton2
各个文件的字节码:
Compiled from "MySingleton1.java"
public class MySingleton1 {
public static MySingleton1 getInstance();
descriptor: ()LMySingleton1;
Code:
0: getstatic #2 // Field ourInstance:LMySingleton1;
3: ifnonnull 16
6: new #3 // class MySingleton1
9: dup
10: invokespecial #4 // Method "<init>":()V
13: putstatic #2 // Field ourInstance:LMySingleton1;
16: getstatic #2 // Field ourInstance:LMySingleton1;
19: areturn
}
and
Compiled from "MySingleton2.java"
public class MySingleton2 {
public static synchronized MySingleton2 getInstance();
descriptor: ()LMySingleton2;
Code:
0: getstatic #2 // Field ourInstance:LMySingleton2;
3: ifnonnull 16
6: new #3 // class MySingleton2
9: dup
10: invokespecial #4 // Method "<init>":()V
13: putstatic #2 // Field ourInstance:LMySingleton2;
16: getstatic #2 // Field ourInstance:LMySingleton2;
19: areturn
}
我只是想增加对java w.r.t的理解。字节码。
如果我的方法错误或者问题太微不足道,请通过评论告诉我。
非常欢迎任何与文档相关的参考,但以下内容除外:
https://en.wikipedia.org/wiki/Java_bytecode https://en.wikipedia.org/wiki/Java_bytecode
https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings
http://www.cnblogs.com/richaaaard/p/6214929.html http://www.cnblogs.com/richaaaard/p/6214929.html