Over a million developers have joined DZone.

Demonstrating when volatile is required

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

In many cases volatile is required when you need a guarantee about visibility of changes between threads. i.e. All threads see a consistent view of the same field. Demonstrating a consistent failure when you don't use volatile is tricky, and likely to be platform specific.

 

An example

The following example show that each thread starts by flipping the value and then stops as each thread has a different view of the field value This works on Java 7 update 2 on Centos 5.7 (x64).

Even incidental change to the code, change the behaviour showing how brittle the example is. I would be interested if others can reproduce this behaviour

 

The code

public class RequiresVolatileMain {
    static boolean value;

    public static void main(String... args) {
        new Thread(new MyRunnable(true), "Sets true").start();
        new Thread(new MyRunnable(false), "Sets false").start();
    }

    private static class MyRunnable implements Runnable {
        private final boolean target;

        private MyRunnable(boolean target) {
            this.target = target;
        }

        @Override
        public void run() {
            int count = 0;
            boolean logged = false;
            while (true) {
                if (value != target) {
                    value = target;
                    count = 0;
                    if (!logged)
                        System.out.println(Thread.currentThread().getName() + ": reset value=" + value);
                } else if (++count % 1000000000 == 0) {
                    System.out.println(Thread.currentThread().getName() + ": value=" + value + " target=" + target);
                    logged = true;
                }
            }
        }
    }
}

As you can see, each thread tries to flip the value whenever it doesn't match the target. When you attempt to run this fails, perhaps not in the way you might expect. If you run this with -XX:+PrintCompilation

Sets true: reset value=true
Sets false: reset value=false
....
Sets true: reset value=true
Sets false: reset value=false
     44    1 %           com.google.code.java.core.threads.RequiresVolatileMain$MyRunnable::run @ 4 (129 bytes)
Sets true: reset value=true
Sets false: reset value=false
....
Sets true: reset value=true
Sets false: reset value=false
Sets true: value=false target=true
Sets false: value=true target=false
...
Sets true: value=false target=true
Sets false: value=true target=false
Not long after the code is compiled, the code starts acting as if it doesn't detect a change even though the value printed is clearly not the target. Exactly why it fails this way is not clear. esp. as the value in the same thread appears to be inconsistent.

The only explanation I can come up with is that if (value != target) has been incorrectly optimised away. Possibly because the only branch which sets this value is not run most of the time.

Just caching the value stops it failing for me, but this is not a proper fix and might fail on a different platform

                // caching the value stops the failure.
                boolean value = RequiresVolatileMain.value;
                if (value != target) {
                    RequiresVolatileMain.value = target;

 

The solution

The solution is to use a volatile variable, in which case it keeps printing that the value is reset as expected.

 

From http://vanillajava.blogspot.com/2012/01/demonstrating-when-volatile-is-required.html

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}