DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Reactive Programming
  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
  • Operator Overloading in Java
  • Redefining DevOps: The Transformative Power of Containerization

Trending

  • Reactive Programming
  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
  • Operator Overloading in Java
  • Redefining DevOps: The Transformative Power of Containerization
  1. DZone
  2. Data Engineering
  3. Data
  4. Demonstrating when volatile is required

Demonstrating when volatile is required

Peter Lawrey user avatar by
Peter Lawrey
·
Feb. 01, 12 · Interview
Like (0)
Save
Tweet
Share
6.85K Views

Join the DZone community and get the full member experience.

Join For Free

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

Printing Cache (computing) Java (programming language) Visibility (geometry) optimization Clear (Unix) Reset (computing) Branch (computer science)

Opinions expressed by DZone contributors are their own.

Trending

  • Reactive Programming
  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
  • Operator Overloading in Java
  • Redefining DevOps: The Transformative Power of Containerization

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: