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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章