Re: is assignment atomic/thread safe?



According to Peter Duniho <NpOeStPeAdM@xxxxxxxxxxxxxxxx>:
But I'm curious how it's relevant to the question of correctness and
synchronization?

The issue may become practical in the following example: thread A
manages a user interface. Thread B runs a long standing computation
which may take quite some time to finish, or may even not finish
at all. The interface contains a "cancel" button.

A simple implementation would use a boolean somewhere which thread B
would poll regularly; B would stop computing as soon as it sees the
boolean set to true. It so happens that making the field volatile is not
sufficient to makes sures that the "cancel" button works, because thread
B could consistently ignore memory updates from A as long as it ignores
other updates from A and does not propagate its own updates, a situation
which may occur on some architectures -- not current x86 hardware, but
vendor make no promise about keeping the proactive update behaviour for
future versions (Intel makes no promise; AMD states explicitely that it
makes no promise).

So synchronization is correct but only relatively to other modifications
which are visible in the Java abstract machine. I.e. if thread A
modifies volatile field F, then thread A must not see the result of any
action from B which logically, in B program order, follows B reading the
new value of F. Some user-visible properties such as heavy CPU
consumption are not part of what a thread in the abstract machine may
see and are thus not covered by the dependency computation which the
"happens-before" predicate incarnates.


But all these mainstream environments have the same issue that the
thread-scheduler is in charge and may well delay execution of any
given thread arbitrarily long in order to satisfy the needs of other
threads.

What I am pointing out is that the delays involved here may be quite
higher than what could "morally" be expected. If I have four CPU cores
and only two "computing" threads then I somehow expect that each will
get a fair amount of clock cycles, and that communications between the
threads should be close to immediate. At least, a user could be
righteously angry at a "cancel" button which took several seconds or
minutes to be taken into account.


Do not get me wrong: I am not trying to criticize the Java memory model.
I _could_ criticize the notion of memory-sharing threads for impeding
the development of highly-parallel machines and clusters, but that's
another debate. What I want to do is to explain that the guarantees
offered by Java "volatile" and "synchronized" do not include any notion
of immediacy.

(In the process of writing these messages, I also learn quite a bit on
the fine details of the memory model in Java so the discussion is not
vain -- at least from my point of view.)


--Thomas Pornin
.