Bass Bass - 1 year ago 112
Java Question

Thread.holdsLock() and lock coarsening

Assume I have 2 adjacent

blocks with a
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
blocks? Will
call still return
, or will the code fail with an exception?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download