[concurrency-interest] Using a volatile variable as a "guard"

Yan Cheng CHEOK yccheok at yahoo.com
Mon Feb 7 03:24:36 EST 2011

Hello all,

I came across the article "Java theory and practice: Fixing the Java Memory Model, Part 2", by Brian Goetz.

I hope I understand section "New guarantees for volatile" correctly. 

I try to use a similar technique as Brian Goetz's. My objective is :

A) Never execute factory's operate member function, if it is a NuclearFactory.

Hence, I try to turn on volatile guard variable isNuclearFactor, before I attempt to construct nuclear factory. This is different from Brian Goetz's.
Brian Goetz only write to volatile variable, after he had finished constructed configOptions.

I feel the following code should work, based on the information picked from Brian Goetz's article.

""Under the new memory model, when thread A writes to a volatile variable V, and thread B reads from V, any variable values that were visible to A at the time that V was written are guaranteed now to be visible to B""

when thread A writes to volatile isNuclearFactory, and thread B reads from isNuclearFactory, factory was visible to A as FoodFactory at the time that isNuclearFactory was written. Hence, factory are guranteed now to be visible to B as FoodFactory too.

I hope I am getting this correctly. Or, do I need to mark factory as volatile too?

void fun_by_thread_A() {
    this.isNuclearFactory = true;
    this.factory = new NuclearFactory();

void fun_by_thread_B() {
    Factory _factory = this.factory;
    if (this.isNuclearFactory) {
        // Do not operate nuclear factory!!!
    // If out-of-order execution happens, _factory might 
    // be NuclearFactory instance.

Factory factory = new FoodFactory();
volatile boolean isNuclearFactory = false;

Thanks and Regards
Yan Cheng CHEOK


More information about the Concurrency-interest mailing list