synchronize字节码解析
源java文件:
public class TestSynchronize {
static volatile int b;
public static void main(String[] args) {
String s = new String("xxx");
int a = 10;
synchronized(s){
a++;
}
b = 10;
}
}
字节码文件:
public class com.learn.test.code.bytecode.TestSynchronize {
static volatile int b;
public com.learn.test.code.bytecode.TestSynchronize();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: new #2 // class java/lang/String
3: dup
4: ldc #3 // String xxx
6: invokespecial #4 // Method java/lang/String."<init>":(Ljava/lang/String;)V
9: astore_1
10: bipush 10
12: istore_2
13: aload_1
14: dup
15: astore_3
16: monitorenter
17: iinc 2, 1
20: aload_3
21: monitorexit
22: goto 32
25: astore 4
27: aload_3
28: monitorexit
29: aload 4
31: athrow
32: bipush 10
34: putstatic #5 // Field b:I
37: return
Exception table:
from to target type
17 22 25 any
25 29 25 any
}
i++对应的字节码如下:
17: iinc 2, 1
20: aload_3
他们被moniterenter和moniterexit如下包围起来:
16: monitorenter
17: iinc 2, 1
20: aload_3
21: monitorexit
还没有评论,来说两句吧...