What kind of a mechanism does a ReentrantLock use? I'm trying to understand where it would show up under a Java Flight Recording. My expectation was that the lock would be under the Java Monitor Wait section but it doesn't appear to be the case.
Background:
I'm trying to debug a problematic ReentrantLock by capturing a java flight recording. The lock itself is very simple:
public class SomeClass {
private final ReentrantLock lock = new ReentrantLock();
public void capture() {
boolean exclusive = someFunction();
try {
if (exclusive) {
lock.lock();
}
// critical code
} finally {
if (exclusive) {
lock.unlock();
}
}
}
}
In my experiment my application should have called the capture
function 2 million times where on some occasions the lock would be activated depending on someFunction()
. As I wasn't getting the expected result, I hardcoded the function to always be true but didn't observe 2 million Java Monitor Waiting events in my recording.
ReentrantLocks do not make use of Java intrinsic monitors. Synchronization through the synchronized
keyword and Locks are different concepts. See also this related answer.
Synchronization through synchronized
(= usage of intrinsic monitors / locks) stores lock information directly on the internal memory representation of an object and is implemented in native code. Locks store lock information in own Java objects and are implemented in Java code. With it, locks are more flexible than the built-in intrinsic monitors. They allow for example mutual exclusion over object boundaries, they make it possible to grant multiple threads concurrent read access and let the developer choose between fair or unfair locking. All things that are not possible with built-in synchronization.
So while a ReentrantLock (as stated in the JavaDoc) has the same basic behavior and semantics as the implicit monitor lock accessed using synchronized
methods and statements, it is implemented in a completely different way.
The gain of flexibility comes at the cost of complexity. While it is realtively simple to track the status of intrinsic monitors, monitoring and detecting or even analysing dead locks for ReentrantLocks is much harder. To my knowledge most monitoring tools (including flight recorder) provide no or only limited support for locks in comparison to the build in intrinsic locks / monitors.
You will come to appreciate the simplicity of the built-in synhronization mechanism, the first time you have to analyse a deadlock in productive code that makes heavy use of ReentrantLocks or other Lock implementations ;-)