Consider the Java example below. Notice that neither of the class member variables are declared to be volatile
. If I am understanding the memory model and "happens before" rules correctly, a Java implementation could optimize the run()
method so that it runs forever, even if another thread calls the stopNow()
method. This can happen because there is nothing in the run()
method that forces the thread to read the value of stop
more than once. Is that correct? If not, why not?
class Example implements Runnable {
boolean stop = false;
int value = 0;
public void stopNow() {
stop = true;
}
public int getValue() {
return value;
}
@Override
public void run() {
// Loop until stop is set to true.
while (!stop) {
++value;
}
return;
}
}
that can be modified by another thread but this is not gurranteed. also this is not thread safe either. To make a variable gurranteed to see from another thread you need to do any of the following
Changes to fields made by one thread are guaranteed to be visible to other threads only under the following conditions:
- A writing thread releases a synchronization lock and a reading thread subsequently acquires that same synchronization lock.
- If a field is declared as volatile, any value written to it is flushed and made visible by the writer thread before the writer
thread performs any further memory operation (i.e., for the purposes
at hand it is flushed immediately). Reader threads must reload the
values of volatile fields upon each access.- The first time a thread accesses a field of an object, it sees either the initial value of the field or a value since written by some other thread.
- As a thread terminates, all written variables are flushed to main memory. For example, if one thread synchronizes on the termination of another thread using Thread.join, then it is guaranteed to see the
effects made by that thread (see §4.3.2).
helpful SO thread
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With