many developers of multi-threaded code are familiar with the idea
that different threads can have a different view of a value they are
holding, this not the only reason a thread might not see a change if it
is not made thread safe. the jit itself can play a part.
when you have multiple threads, they will attempt to minimise how
much they will interact e.g. by trying to access the same memory. to do
this they have a separate local copy e.g. in level 1 cache. this cache
is usually eventually consistent. i have seen short periods of between
one micro-second and up to 10 milli-seconds where two threads see
different values. eventually the thread is context switched, the cache
cleared or updated. there is no guarantee as to when this will happen
but it is almost always much less than a second.
the java memory model says there is no guarantee that a field which
is not thread safe will ever see an update. this allows the jit to make
an optimisation where a value only read and not written to is
effectively inlined into the code. this means that even if the cache is
updated, the change might not be reflected in the code.
this code will run until a boolean is set to false.
this code repeatedly performs some work which has no impact on
memory. the only difference it makes is how long it takes. by taking
longer, it determines whether the code in run() will be optimised before
or after running is set to false.
if i run this with 10 or 100 and -xx:+printcompilation i see
if i run this with 1000 you can see that the run() hasn’t been compiled and the thread stops
once the thread has been compiled, the change is never seen even though the thread will have context switched etc. many times.
the simple solution is to make the field volatile. this
will guarantee the field’s value consistent, not just eventually
consistent which is what the cache might do for you.
while there are many examples of question like; why doesn’t my thread
stop? the answer has more to do with java memory model which allows the
jit “inline” the fields that it does the hardware and having multiple
copies of the data in different caches.