Simultaneous reading and changing the variable by different threads

I am interested in the situation where one thread is waiting for change of a variable in the while loop:

while (myFlag == false) {
    // do smth
}

It is repeating an infinite number of times.

In the meantime, another thread have changed the value of this variable:

myFlag = true;

Can the reader-thread see the result of changing the value of the variable in the other thread if this variable is NOT volatile? In general, as I understand it will never happen. Or am I wrong? Then when and under what circumstances, the first thread can see the change in the variable and exit the loop? Is this possible without using volatile keyword? Does size of processor's cache play role in this situation?

Please explain and help me understand! Thank you in advance!!

Jon Skeet
people
quotationmark

Can the reader-thread see the result of changing the value of the variable in the other thread if this variable is NOT volatile?

It may be able to, yes. It's just that it won't definitely see the change.

In general, as I understand it will never happen.

No, that's not the case.

You're writing to a variable and then reading from it in a different thread. Whether or not you see it will depend on the exact processor and memory architecture involved. Without any memory barriers involved, you aren't guaranteed to see the new value - but you're certainly not guaranteed not to see it either.

people

See more on this question at Stackoverflow