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?
The holdLock() method of thread class returns true if the current thread holds the monitor lock on the specified object.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With