>Just looking at your final example, I can't understand how you can say that is unsafe
Let me change the example a bit. Say we have two locks aL and bL, that we must always acquire in the order aL first and then bL.
Following the rule, say we write code like this:
import java.util.concurrent.locks.ReentrantLock;
class X {
private static ReentrantLock aL = new ReentrantLock();
private static ReentrantLock bL = new ReentrantLock();
static int x = 0;
static int c = 0;
static public void main(String[] args) {
for(aL.lock(); c < 100; c++) {
synchronized(bL) {
x = x + 0x42;
}
}
aL.unlock();
}
}
If I understood it right, the blog post was asking a question whether JVM can transform this to: import java.util.concurrent.locks.ReentrantLock;
class X {
private static ReentrantLock aL = new ReentrantLock();
private static ReentrantLock bL = new ReentrantLock();
static int x = 0;
static int c = 0;
static public void main(String[] args) {
synchronized(bL) {
for(aL.lock(); c < 100; c++) {
x = x + 0x42;
}
aL.unlock();
} // end synnchronized
}
}
Since the locks are now acquired in a different order, does that not qualify as observable behavior?