Is it possible to prevent out-of-order execution by using single volatile
- by Yan Cheng CHEOK
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.