|
monitorenter 指令可以理解为加锁,monitorexit 可以理解为释放锁。
进入 monitorenter 指令后,线程将持有 Monitor 对象,退出 monitorenter 指令后,线程将释放该 Monitor 对象。
对于方法:出现了ACC_SYNCHRONIZED 标识。
当出现了 ACC_SYNCHRONIZED 标识符的时候,Jvm 会隐式调用 monitorenter 和 monitorexit。在执行同步方法前会调用 monitorenter,在执行完同步方法后会调用 monitorexit,释放 Monitor 对象。
你可以发现,不管是同步代码块还是同步方法,都和 Monitor 对象有关系。
那么问题又来了!!
问题:这个 Monitor 对象是啥呢?monitorenter 和 monitorexit 又是什么呢?
4.1、monitorenter
直接看 JVM 规范里对它的描述,地址在文末:
-
Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:
-
If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
-
If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
-
If another thread already owns the monitor associated with objectref, the thread blocks until the monitor's entry count is zero, then tries again to gain ownership.
-
翻译:每一个对象都会和一个监视器 Monitor 关联。监视器被占用时会被锁住,其他线程无法来获取该 Monitor。当 JVM 执行某个线程的某个方法内部的 onitorenter 时,它会尝试去获取当前对象对应的 Monitor 的所有权。
执行过程如下:
-
若 Monior 的进入数为 0,线程可以进入 Monitor,并将 monitor 的进入数置为 1。当前线程成为 Monitor 的 owner 拥有者。
-
若线程已拥有 Monitor 的所有权,允许它重入 Monitor,则进入 Monitor 的进入数加 1。
-
若其他线程已经占有 Monitor 的所有权,那么当前尝试获取 Monitor 的所有权的线程会被阻塞,直到 Monitor 的进入数变为 0,才能重新尝试获取 Monitor 的所有权。
4.2、monitorexit
看 JVM 规范里对它的描述,地址在文末:
-
The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref.
-
The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.
执行过程如下:
-
能执行 monitorexit 指令的线程一定是拥有当前对象的 Monitor 的所有权的线程。
-
执行 monitorexit 时会将 Monitor 的进入数减 1。当 Monitor 的进入数减为 0 时,当前线程退出 Monitor,不再拥有 Monitor 的所有权,此时其他被这个 Monitor 阻塞的线程可以尝试去获取这个 Monitor 的所有权。
4.3、Monitor 监视器
每个对象都会关联一个 Monitor 对象,也叫做监视器。
在 HotSpot 虚拟机中,Monitor 是由 ObjectMonitor 实现的。其源码是用 c++来实现的,位于 HotSpot 虚拟机源码 ObjectMonitor.hpp 文件中(路径:src/share/vm/runtime/objectMonitor.hpp)
ObjectMonitor 主要数据结构如下:

(编辑:南昌站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|