Bass Bass - 5 months ago 28
Java Question

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?

Answer

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.

Further more, 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.