[concurrency-interest] Fwd: Should I avoid compareAndSet with value-based classes?

Andrew Haley aph at redhat.com
Fri Jul 7 05:20:25 EDT 2017

On 06/07/17 20:12, Gil Tene wrote:

> The answer to this is generally "But… concurrency!". Which is why
> this is an ok place to chat about it probably. With no identity, how
> do you achieve atomic updates? Michael's MutableClock example
> (scroll down) of wanting to (potentially concurrently) add duration
> amounts to some notion of a point in time, while avoiding the
> potential for "losing" an add racy situations, requires some sort of
> synchronization. Since Instant is not mutable, and we are
> necessarily trying to atomically replace one Instant value with
> another, we have a problem with the notion that these values have no
> identity (and therefore no way to do a proper CAS on).

In practice it doesn't matter, because you don't need to CAS a
reference to an Instant: all you need to do is to wrap all of the
updates to that reference in synchronized blocks.  Readers don't need
anything more than for that reference to be volatile.  The
immutability of Instant and the sequential consistency of volatile
provide all the guarantees that anyone needs or are possible.

I doubt that a synchronized block is going to perform much more badly
than spinning in a CAS loop, especially in the presence of high
contention.  In the many readers/few writers situation that Michael
describes this is the optimal solution.

Andrew Haley
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671

More information about the Concurrency-interest mailing list