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

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.

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.

Moving towards a private or Hybrid cloud infrastructure model? Get started with our OpenStack Deployment Models guide to learn the proper deployment model for your organization.

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}