Is it possible to prevent out-of-order execution by using single volatile

Posted by Yan Cheng CHEOK on Stack Overflow See other posts from Stack Overflow or by Yan Cheng CHEOK
Published on 2011-01-31T15:43:00Z Indexed on 2011/02/01 15:25 UTC
Read the original article Hit count: 294

Filed under:
|

By referring article, it is using a pair of volatile to prevent out-of-order execution. I was wondering, is it possible to prevent it using single volatile?

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

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

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

The reason I ask, is because I have a single guard flag (similar to isNuclearFactory flag), to guard against multiple variables (similar to many Factory). I do not wish to mark all the Factory as volatile.

Or, shall I fall into the following solution?

void fun_by_thread_1() {
    try {
        writer.lock();
        this.isNuclearFactory = true;
        this.factory = new NuclearFactory();
    } finally {
        writer.unlock();
    }
}

void fun_by_thread_2() {
    try {
        reader.lock();
        Factory _factory = this.factory;
        if (this.isNuclearFactory) {
            // Do not operate nuclear factory!!!
            return;
        }
    } finally {
        reader.unlock();
    }
    _factory.operate();
}

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

P/S: I know instanceof. Factory is just an example to demonstrate of out-of-order problem.

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading