Synchronization in compiling

Synchronous in method

1
2
3
4
int i;
synchronized int fun() {
return ++i;
}

javap

1
2
3
4
5
6
7
8
9
10
11
12
synchronized int fun();
Code:
0: aload_0
1: dup
// Field i:I
2: getfield #2
5: iconst_1
6: iadd
7: dup_x1
// Field i:I
8: putfield #2
11: ireturn

synchronized method is simply distinguished
in the run-time constant pool by the ACC_SYNCHRONIZED flag

Synchronous in block

1
2
3
4
5
6
int i;
void fun(Object obj, int j) {
synchronized(obj) {
i+=j;
}
}

javap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void fun(java.lang.Object, int);
Code:
0: aload_1
1: dup
2: astore_3
3: monitorenter
4: aload_0
5: dup
// Field i:I
6: getfield #2
9: iload_2
10: iadd
// Field i:I
11: putfield #2
14: aload_3
15: monitorexit
16: goto 26
19: astore 4
21: aload_3
22: monitorexit
23: aload 4
25: athrow
26: return
Exception table:
from to target type
4 16 19 any
19 23 19 any

monitorexit will be executed definitely
If not exit normally, #25 will throw exception