今天在学习java原子类的时候,遇到了这篇博客,看到了同步代码块和同步方法的区别,之前没有意识到,这里记录下。
public class CP {
private int i = 0;
public synchronized int synchronizedMethodGet() {
return i;
}
public int synchronizedBlockGet() {
synchronized (this) {
return i;
}
}
}
从功能角度来说,上面两种方式没有差别,都能保证方法执行时候的原子性。从性能上来看,同步方法比同步代码块更有优势。我们使用JDK提供的javap命令,查看生成的字节码。
E:\code_space\test\bin>javap -c CP
Compiled from "CP.java"
public class CP {
public CP();
Code:
0: aload_0
1: invokespecial #10 // Method java/lang/Object."<init>":()V
4: aload_0
5: iconst_0
6: putfield #12 // Field i:I
9: return
public synchronized int synchronizedMethodGet();
Code:
0: aload_0
1: getfield #12 // Field i:I
4: ireturn
public int synchronizedBlockGet();
Code:
0: aload_0
1: dup
2: astore_1
3: monitorenter
4: aload_0
5: getfield #12 // Field i:I
8: aload_1
9: monitorexit
10: ireturn
11: aload_1
12: monitorexit
13: athrow
Exception table:
from to target type
4 10 11 any
11 13 11 any
}
明显可以看到:使用同步代码块,产生的字节码数更多;而同步方法则很少。