JUC编程之——synchronized的底层实现与分析

1 synchronized关键字

synchronized 是 Java 中的关键字,是一种同步锁(也是一种悲观锁)。它修饰的对象有以下几种:

  • 作用于实例方法,当前实例加锁,进入同步代码前要获得当前实例的锁——对象锁
  • 作用于代码块,对括号里配置的对象加锁——对象锁
  • 作用于静态方法,当前类加锁,进去同步代码前要获得当前类对象的锁——类锁

注:synchronized不能修饰变量;

2 javap指令

javap是jdk自带的反解析工具。 它的作用就是根据class字节码文件,反解析出当前类对应的code区(汇编指令)、本地变量表、异常表和代码行偏移量映射表、常量池等等信息。

javap -c
  • -c代表对代码进行反汇编;
  • javap -v ***.class文件反编译
  • -v -verbose 输出附加信息,如行号、本地变量表、反汇编等更加详细的信息;

3 从字节码角度分析synchronized实现

3.1 同步代码块

代码示例

public class LockSyncTest {

    // 一个实例对象
    Object object = new Object();

    public void m1(){
        // 同步代码块
        synchronized (object) {
            System.out.println("这里是同步代码块");
        }
    }

    public static void main(String[] args) {

    }
}

反编译

javap -c LockSyncTest.class

生成内容

Compiled from "LockSyncTest.java"
public class LockSyncTest {
  java.lang.Object object;

  public LockSyncTest();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."":()V
       4: aload_0
       5: new           #2                  // class java/lang/Object
       8: dup
       9: invokespecial #1                  // Method java/lang/Object."":()V
      12: putfield      #3                  // Field object:Ljava/lang/Object;
      15: return

  public void m1();
    Code:
       0: aload_0
       1: getfield      #3                  // Field object:Ljava/lang/Object;
       4: dup
       5: astore_1
       // 获得监视器并进入
       6: monitorenter
       7: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;        
      // here
      10: ldc           #5                  // String 这里是同步代码块
      12: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      15: aload_1
      // 锁退出
      16: monitorexit
      17: goto          25
      20: astore_2
      21: aload_1
      // 底层做了异常处理 如果程序出现异常 底层也要保证释放锁
      22: monitorexit
      23: aload_2
      24: athrow
      25: return
    Exception table:
       from    to  target type
           7    17    20   any
          20    23    20   any

  public static void main(java.lang.String[]);
    Code:
       0: return
}

两个重要指令

  • monitorenter,获得锁;
  • monitorexit,释放锁(两个,一个底层实现发生异常时也要释放锁);

一定是一个enter两个exit么?
——不一定,如果自己在同步代码块throw异常,只有一个enter一个exit;

3.2 普通同步方法

代码示例

public class LockSyncTest {


    // 普通同步方法
    public synchronized void m2(){
        System.out.println("普通同步方法");
    }

    public static void main(String[] args) {

    }
}


反编译

javap -v LockSyncTest.class

生成内容

调用指令将会检查方法的ACC_SYNCHRONIZED访问标志是否被设置,如果设置了,执行线程会将先持有monitor然后再执行方法,最后再方法完成时(无论是正常完成还是非正常完成)时释放monitor;

Classfile out/production/ch16/LockSyncTest.class
  Last modified 2023-4-11; size 608 bytes
  MD5 checksum ff2328e7a59f847a473b7ed814cc108b
  Compiled from "LockSyncTest.java"
public class LockSyncTest
  SourceFile: "LockSyncTest.java"
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #6.#21         //  java/lang/Object."":()V
   #2 = Fieldref           #22.#23        //  java/lang/System.out:Ljava/io/PrintStream;
   #3 = String             #24            //  普通同步方法
   #4 = Methodref          #25.#26        //  java/io/PrintStream.println:(Ljava/lang/String;)V        
   #5 = Class              #27            //  LockSyncTest
   #6 = Class              #28            //  java/lang/Object
   #7 = Utf8               <init>
   #8 = Utf8               ()V
   #9 = Utf8               Code
  #10 = Utf8               LineNumberTable
  #11 = Utf8               LocalVariableTable
  #12 = Utf8               this
  #13 = Utf8               LLockSyncTest;
  #14 = Utf8               m2
  #15 = Utf8               main
  #16 = Utf8               ([Ljava/lang/String;)V
  #17 = Utf8               args
  #18 = Utf8               [Ljava/lang/String;
  #19 = Utf8               SourceFile
  #20 = Utf8               LockSyncTest.java
  #21 = NameAndType        #7:#8          //  "":()V
  #22 = Class              #29            //  java/lang/System
  #23 = NameAndType        #30:#31        //  out:Ljava/io/PrintStream;
  #24 = Utf8               普通同步方法
  #25 = Class              #32            //  java/io/PrintStream
  #26 = NameAndType        #33:#34        //  println:(Ljava/lang/String;)V
  #27 = Utf8               LockSyncTest
  #28 = Utf8               java/lang/Object
  #29 = Utf8               java/lang/System
  #30 = Utf8               out
  #31 = Utf8               Ljava/io/PrintStream;
  #32 = Utf8               java/io/PrintStream
  #33 = Utf8               println
  #34 = Utf8               (Ljava/lang/String;)V
{
  public LockSyncTest();
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."":()V
         4: return
      LineNumberTable:
        line 1: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       5     0  this   LLockSyncTest;

  public synchronized void m2();
    // ACC_SYNCHRONIZED标识
    flags: ACC_PUBLIC, ACC_SYNCHRONIZED
    Code:
      stack=2, locals=1, args_size=1
         0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;      
         3: ldc           #3                  // String 普通同步方法
         5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
         8: return
      LineNumberTable:
        line 6: 0
        line 7: 8
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       9     0  this   LLockSyncTest;

  public static void main(java.lang.String[]);
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=0, locals=1, args_size=1
         0: return
      LineNumberTable:
        line 11: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       1     0  args   [Ljava/lang/String;
}

3.3 静态同步方法

代码示例

public class LockSyncTest {


    // 静态同步方法
    public static synchronized void m3(){
        System.out.println("静态同步方法");
    }

    public static void main(String[] args) {

    }
}


反编译

javap -v LockSyncTest.class

生成内容

ACC_STATIC, ACC_SYNCHRONIZED标识符,区分方法是否为静态同步方法;

Classfile out/production/ch16/LockSyncTest.class
  Last modified 2023-4-11; size 590 bytes
  MD5 checksum e551241d2333dd7b754d24e72063d547
  Compiled from "LockSyncTest.java"
public class LockSyncTest
  SourceFile: "LockSyncTest.java"
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #6.#21         //  java/lang/Object."":()V
   #2 = Fieldref           #22.#23        //  java/lang/System.out:Ljava/io/PrintStream;
   #3 = String             #24            //  静态同步方法
   #4 = Methodref          #25.#26        //  java/io/PrintStream.println:(Ljava/lang/String;)V        
   #5 = Class              #27            //  LockSyncTest
   #6 = Class              #28            //  java/lang/Object
   #7 = Utf8               <init>
   #8 = Utf8               ()V
   #9 = Utf8               Code
  #10 = Utf8               LineNumberTable
  #11 = Utf8               LocalVariableTable
  #12 = Utf8               this
  #13 = Utf8               LLockSyncTest;
  #14 = Utf8               m3
  #15 = Utf8               main
  #16 = Utf8               ([Ljava/lang/String;)V
  #17 = Utf8               args
  #18 = Utf8               [Ljava/lang/String;
  #19 = Utf8               SourceFile
  #20 = Utf8               LockSyncTest.java
  #21 = NameAndType        #7:#8          //  "":()V
  #22 = Class              #29            //  java/lang/System
  #23 = NameAndType        #30:#31        //  out:Ljava/io/PrintStream;
  #24 = Utf8               静态同步方法
  #25 = Class              #32            //  java/io/PrintStream
  #26 = NameAndType        #33:#34        //  println:(Ljava/lang/String;)V
  #27 = Utf8               LockSyncTest
  #28 = Utf8               java/lang/Object
  #29 = Utf8               java/lang/System
  #30 = Utf8               out
  #31 = Utf8               Ljava/io/PrintStream;
  #32 = Utf8               java/io/PrintStream
  #33 = Utf8               println
  #34 = Utf8               (Ljava/lang/String;)V
{
  public LockSyncTest();
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."":()V
         4: return
      LineNumberTable:
        line 1: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       5     0  this   LLockSyncTest;

  public static synchronized void m3();
    // ACC_STATIC, ACC_SYNCHRONIZED标识符
    flags: ACC_PUBLIC, ACC_STATIC, ACC_SYNCHRONIZED
    Code:
      stack=2, locals=0, args_size=0
         0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;      
         3: ldc           #3                  // String 静态同步方法
         5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
         8: return
      LineNumberTable:
        line 6: 0
        line 7: 8

  public static void main(java.lang.String[]);
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=0, locals=1, args_size=1
         0: return
      LineNumberTable:
        line 11: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       1     0  args   [Ljava/lang/String;
}

4 synchronized锁的是什么

Q:为什么任何一个对象都可以成为一个锁?
A:在HotSpot虚拟机中,monitor采用ObjectMonitor实现;

4.1 什么是管程?

管程也叫监视器(Monitors),是一种程序结构,结构内的多个子程序(对象或模块)形成的多个工作线程互斥访问共享资源。

这些共享资源一般是硬件设备或一群变量。对共享变量能够进行的所有操作集中在一个模块中。(把信号量及其操作原语“封装”在一个对象内部)管程实现了在一个时间点,最多只有一个线程在执行管程的某个子程序。管程提供一种机制,管程可以看作一个软件模块,它是将共享的变量和对于这些共享变量的操作封装起来,形成一个具有一定接口的功能模块,进程可以调用管程来实现进程级别的并发控制


4.2 底层C++代码解读

ObjectMonitor.java -> ObjectMonitor.cpp ->ObjectMonitor.hpp

ObjectMonitor.hpp部分源码:

  ObjectMonitor() {
    _header       = NULL;
    _count        = 0;
    _waiters      = 0,
    _recursions   = 0;
    _object       = NULL;
    _owner        = NULL;
    _WaitSet      = NULL;
    _WaitSetLock  = 0 ;
    _Responsible  = NULL ;
    _succ         = NULL ;
    _cxq          = NULL ;
    FreeNext      = NULL ;
    _EntryList    = NULL ;
    _SpinFreq     = 0 ;
    _SpinClock    = 0 ;
    OwnerIsThread = 0 ;
    _previous_owner_tid = 0;
  }


ObjectMonitor中几个关键的属性:

JUC编程之——synchronized的底层实现与分析_第1张图片

你可能感兴趣的:(java,jvm,开发语言)