ITEM 78: SYNCHRONIZE ACCESS TO SHARED MUTABLE DATA
313
The problem is that in the absence of synchronization, there is no guarantee as
to when, if ever, the background thread will see the change in the value of
stopRequested
made by the main thread. In the absence of synchronization, it’s
quite acceptable for the virtual machine to transform this code:
while (!stopRequested)
i++;
into this code:
if (!stopRequested)
while (true)
i++;
This optimization is known as
hoisting
, and it is precisely what the OpenJDK
Server VM does. The result is a
liveness failure
: the program fails to make prog-
ress. One way to fix the problem is to synchronize access to the
stopRequested
field. This program terminates in about one second, as expected:
Do'stlaringiz bilan baham: