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

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

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.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

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 }}