在学习并发安全编程时,无意发现了一遍关于同步的文章,现记录下来。
package others;
public class CP {
private int i = 0;
public synchronized int synchronizedMethodGet() {
return i;
}
public int synchronizedBlockGet() {
synchronized (this) {
return i;
}
}
}
上面的类中有两个同步方法,从功能上来说两种方法没有差别,都可以保证数据的原子性。但是从性能上来说,同步方法要比同步块更快一些。通过查看这两个方法所产生的字节码文件进行对比:
D:\Workspaces\test\java_concurrent\bin\others>javap -c CP
Compiled from "CP.java"
public class others.CP {
public others.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
}
从字节码文件中可以看出,同步代码块比同步方法生成更多的字节文件,而且还生成了Exception table;并且注意查看class文件,在synchronizedBlockGet下有3: monitorenter、9: monitorexit、12: monitorexit有同步监视器的显示进入进出,所以这些操作消耗了部分资源,即同步快性能更差一些。