We have two threads that execute the sequences below, without any synchronization:
x = y = 0 | |
Thread 1 | Thread 2 |
x = 1 j = y |
y = 1 i = x |
Is it possible for both i and j to be 0 if print is called in another thread?
Sadly the answer is YES! If the code is unsynchronized and you don’t use volatile variables the compiler is free to optimize this code, it can even reorder the instructions. Even if the compiler does not reorder the instructions, it is very possible that the x=1 or y=1 assignments are done in the local caches only and are not visible to the other threads until later on.
The moral of this story?
Unsynchronized code may seem intuitive but it is not! Because of hardware and implementation details the code is totally unpredictable. Always synchronize your multi-threaded code.