Java synchronize method与synchronize block的不同

在学习并发安全编程时,无意发现了一遍关于同步的文章,现记录下来。

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: monitorenter9: monitorexit12: monitorexit有同步监视器的显示进入进出,所以这些操作消耗了部分资源,即同步快性能更差一些。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值