Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.holdsLock() and lock coarsening

Assume I have 2 adjacent synchronized blocks with a Thread.holdsLock() call between them:

final Object lock = new Object();
// ...
synchronized (lock) {
    // do stuff
}
if (Thread.holdsLock(lock)) {
    throw new IllegalStateException();
}
synchronized (lock) {
    // do more stuff
}

Now, what if at some point the JVM decides to coarsen the lock and merge the above synchronized blocks? Will Thread.holdsLock() call still return false, or will the code fail with an exception?

like image 594
Bass Avatar asked Jun 14 '16 12:06

Bass


People also ask

How do you check if a thread holds a lock or not?

The holdLock() method of thread class returns true if the current thread holds the monitor lock on the specified object.

What is lock in multithreading?

A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first.

Where are threads stored in Java?

Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects referred from the method that are in a heap.


1 Answers

A good question, I would say no based on the JSR 133 Cookbook. The grid shows that a NormalLoad cannot be reordered above a MonitorExit. In this case the read would, in theory, be the lock.

Furthermore, Rafael Winterhalter mentions in a presentation regarding the Java memory model that native calls cannot be reordered, but I am having trouble finding documentation to prove this.

like image 156
John Vint Avatar answered Oct 05 '22 15:10

John Vint