[concurrency-interest] JDK 9's compareAndSet vs compareAndExchange

Aleksey Shipilev shade at redhat.com
Fri Sep 23 05:16:38 EDT 2016

On 09/23/2016 09:11 AM, Dávid Karnok wrote:
> Thanks for the information.
> FYI, I do have places where compareAndExchange is useful and not part of
> a loop:
> public static boolean setOnce(VarHandle h, Object instance, Subscription
> s) {
>     Subscription o = (Subscription)h.compareAndExchange(instance, null, s);
>     if (o != null) {
>         s.cancel();
>         if (o != CANCELLED) {
>             CatchAll.onError(new IllegalStateException("Subscription
> already set!"));
>         }
>         return false;
>     }
>     return true;
> }

This seems like a fair use.

Not sure this is significantly better than compareAndSet + re-read on
failure, because the state changes seem only monotonic (e.g. from null
to one canonical instance), and re-read would not produce false results.

The caveat for VarHandles though is, $h is better to come from the
(static final) constant, otherwise you will have lots of unfolded checks
in VH mechanics, which may affect performance even more.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20160923/e0a2d3d2/attachment.sig>

More information about the Concurrency-interest mailing list