Lets say i have a thread running like this:
private boolean working = true;
@Override public void run() {
working = true;
// do something
working = false;
....
}
and in my main Thread i’m constantly putting out the state of working with
while(threadClassObject.isWorking()) {
System.out.println(threadClassObject.isWorking());
}
would this work? I tried this example and it seems to work. But is there a way that this could crash? What e.g. happens if the thread is in the process of changing working while at the exact same time the mainThread tries to read it?
The ans to your question is that it might be working but the above code is a risky code and can break any day. Try making
workingvolatilelikeWhat e.g. happens if the thread is in the process of changing working while at the exact same time the mainThread tries to read it?Assignment operation is an atomic operation. So if you have single cpu, two threads can never collide while accessing the variable. If you have more than one cpu, two threads can collide while accessing the variable. For both cases,
volatilewill make sure that the value is visible to other threads.NOTE:
volatileis good in your situation but if you have more complex data to share across thread try looking into thisEdit:
Adding the comment also part of the soln. to make it more clear.
Basically bcoz of optimization at cpu level, values changed my one thread might not be visible to another. A good example is cpu cache bcoz optimization the values are never reflected in ram where the other thread might be reading. Volatile tells that this variable’s value can be changed outside the scope of current thread so no such optimization is done…