Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Roach Motel and the Java Memory Model

DZone's Guide to

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.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

First, 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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,jvm ,roach motel ,tutorial ,java memory model

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}