[concurrency-interest] Does factoring out VarHandle-based manipulations cause performance penalties?

Dávid Karnok akarnokd at gmail.com
Wed Aug 9 04:17:17 EDT 2017


In my codebase, targeting Java 9, I often have to perform the same set of
atomic operations on fields of various classes, for example, a deferred
cancellation of Flow.Subscriptions:

Flow.Subscription upstream;
static final VarHandle UPSTREAM;

@Override
public void cancel() {
    Flow.Subscription a = (Flow.Subscription)UPSTREAM.getAcquire(this);
    if (a != CancelledSubscription.INSTANCE) {
        a = (Flow.Subscription)UPSTREAM.getAndSet(this,
CancelledSubscription.INSTANCE);
        if (a != null && a != CancelledSubscription.INSTANCE) {
            a.cancel();
        }
    }
}

Refactored into:

final class SubscriptionHelper {

    public static void cancel(Object target, VarHandle handle) {
        Flow.Subscription a = (Flow.Subscription)handle.getAcquire(target);
        if (a != CancelledSubscription.INSTANCE) {
            a = (Flow.Subscription)handle.getAndSet(target,
CancelledSubscription.INSTANCE);
            if (a != null && a != CancelledSubscription.INSTANCE) {
                a.cancel();
            }
        }
    }
}

@Override
public void cancel() {
    SubscriptionHelper.cancel(this, UPSTREAM);
}


I'd think JIT can and will inline SubscriptionHelper.cancel to all its use
sites, but the fact that the cancel method no longer has "this" but an
arbitrary target Object, my concern is that the optimizations may not
happen.

I haven't noticed any performance penalties so far but I remember Aleksey
Shipilev mentioning somewhere, some time ago, a warning about such
out-of-context VarHandle uses.

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


More information about the Concurrency-interest mailing list