Roach Motel and the Java Memory Model
This demo of the JMM's roach motel in action explains how it works and why it's worthwhile to know about reordering with synchronized blocks.
Join the DZone community and get the full member experience.
Join For FreeFirst, let's determine the meaning of roach motel reordering. The roach motel is an approach that lets the compiler move lines of code into synchronized blocks while moving out is disabled. Also, with statements inside a synchronized block, as long as the modification is sequentially consistent, it means that the specific statement is not visible from another place in the code that shares the happens-before relationship with the block.
The roach motel in the Java Memory Model is very similar to a trap for roaches — blocks of code can be moved into synchronized blocks, but they can't be moved out.
Let's consider this code snippet:
a = 1;
synchronized(objMonitor) {
b = b + someMethod();
}
c = 1;
The compiler can move assigning to the variable a:
synchronized(objMonitor) {
a = 1;
b = b + someMethod();
}
c = 1;
It's also a possible version of reordering to the situation above:
synchronized(objMonitor) {
b = b + someMethod();
a = 1;
}
c = 1;
The same rule is applicable to variable c:
a = 1;
synchronized(objMonitor) {
c = 1;
b = b + someMethod();
}
a = 1;
synchronized(objMonitor) {
b = b + someMethod();
c = 1;
}
Access to variables that were moved into the synchronized block can happen in any order, and if the variable was moved into the synchronized block, it can't be moved out.
This leads to a thought: There are two types of programmers — the first naively think that the order of lines of code will be respected in a written order, and the second know what reordering is.
Opinions expressed by DZone contributors are their own.
Comments