What is a structured locking in the JVM specification?
陈雨亭
chenyt at cs.sjtu.edu.cn
Thu May 18 00:34:01 UTC 2017
Hi, I read the JVM specification and hope to get some clarifications here.
The original explanation about structured locking is given as: "Structured
locking is the situation when, during a method invocation, every exit on a
given monitor matches a preceding entry on that monitor. Since there is no
assurance that all code submitted to the Java Virtual Machine will perform
structured locking, implementations of the Java Virtual Machine are
permitted but not required to enforce both of the following two rules
guaranteeing structured locking. Let T be a thread and M be a monitor. Then:
(1) The number of monitor entries performed by T on M during a method
invocation must equal the number of monitor exits performed by T on M during
the method invocation whether the method invocation completes normally or
abruptly. (2) At no point during a method invocation may the number of
monitor exits performed by T on M since the method invocation exceed the
number of monitor entries performed by T on M since the method invocation."
(https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.11.10
)
According to the definition, it seems that a structured locking appears
like: T {...Monitorenter r0; …monitorenter r0; …; monitorexit r0; …
monitorexit r0;...}
Two questions:
(1) I’m a little curious whether a structured locking can be composed by
the following instructions, as two objects are not nestedly locked:
Monitorenter r0; monitorenter r2; …; monitorexit r0; monitorexit r2;
Should this sequence be accepted or rejected? At runtime or during the
verification time? Will this locking structure cause deadlocks?
(2) Rule 1 is not really used to guaranteeing structured locking, at least
from its definition.
Besides, I retested some programs on HotSpot and IBM's J9. It seems that
HotSpot takes Rule 1 (rule1 is stricter than rule2, and HotSpot throws out
an IllegalMonitorStateException at runtime), and J9 only takes Rule 2
(accepting the program). As the IllegalMonitorStateException can be caught
(with further exception handlings), some of my programs run quite
differently on the two platforms.
f(){
monitorenter r0;
}
g(){
f();
monitorexit r0;
}
Yuting
More information about the jls-jvms-spec-comments
mailing list