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

Dávid Karnok akarnokd at gmail.com
Fri Sep 23 05:36:57 EDT 2016


>
> 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 code supposed to detect multiple calls to a setOnce. If the witness is
not the CANCELLED instance, that is considered a bug (detected by looping a
bit in unit tests - not perfect but helped many times).


> 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.
>
>
I was considering asking this separately. Former code used either
AtomicReferenceFieldUpdater + instance or AtomicReference as input
parameter. I was under the assumption that the method would get inlined and
the $h is $this.field and $instance becomes $this.

public static <T> boolean setOnce(AtomicReferenceFieldUpdater<T,
Flow.Subscription>
h, T instance, Flow.Subscription s) {
    if (h.compareAndSet(instance, null, s)) {
        s.cancel();
        if (h.get(instance) != CANCELLED) {
            CatchAll.onError(new IllegalStateException("Subscription
already set!"));
        }
        return false;
    }
    return true;
}

final class SomeOperator implements Flow.Subscriber<Object> {
    volatile Flow.Subscription s;
    static final AtomicReferenceFieldUpdater<SomeOperator, Flow.Subscription>
S
        = AtomicReferenceFieldUpdater.newUpdater(SomeOperator.class,
Flow.Subscription.class,
"s");

   public void onSubscribe(Flow.Subscription s) {
       if (SubscriptionHelper.setOnce(S, this, s)) {
           s.request(Long.MAX_VALUE);
       }
   }

   // ...
}





> Thanks,
> -Aleksey
>
>


-- 
Best regards,
David Karnok
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20160923/f53e4248/attachment.html>


More information about the Concurrency-interest mailing list