On 10/30/2016 05:55 AM, Peter Veentjer wrote:
> Let me clarify.
> The discussion is around removing the volatile read in the inc method.

Ah, sorry I misinterpreted the question. It usually goes the other way:
the reads vastly outnumber the writes.

Well, since the writer is single-threaded, there is no need for a
volatile/atomic reads/updates in the inc(). But I think it's useless to
optimize the volatile reads there, because you have the impending
volatile/release store, which would dominate the cost. So, having that
in mind, the better strategy might be dispensing with Atomic on every
inc()? The excess branch might be much less hassle than a
volatile/release store.

public class Counter {
    private long local;
    private volatile long publish;

    public void inc(){
        long n = local++;
        if ((n & 0xFF) == 0) {
           publish = n;
        }
    }

    public long get() {
        return publish;
    }
}

...with VarHandles, you can even collude the access modes:

public class Counter {
    static final VH = <get_VH_to_local>;
    private long local;

    public void inc(){
        long n = VH.get(this);
        n++;
        if ((n & 0xFF) == 0) {
           VH.set(this, n);
        } else {
           VH.set{Volatile,Release,Opaque}(this, n);
        }
    }

    public long get(){
        return VH.get{Volatile,Acquire,Opaque}(this);
    }
}

...with some choice of the modes.

>  A counter could be incremented >100k times a second and we don't want a
>  counter to cause too much of a performance degradation. A counter will
>  always be incremented by the same thread.

There is a subtle difference between "a single writer to Counter", and
"each thread gets its own Counter". I would venture to guess that
(false) sharing in your case should be the concern, not the cost of
volatile ops.

Having a referenced AtomicLong instead of padded out "local" field would
set you up for false sharing very nicely :)

Thanks,
-Aleksey

-- 
You received this message because you are subscribed to the Google Groups 
"mechanical-sympathy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to mechanical-sympathy+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to