Let me clarify.

The discussion is around removing the volatile read in the inc method.

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.

The get method will only be called every X seconds. So a volatile read is 
fine.


On Saturday, October 29, 2016 at 11:13:38 AM UTC+3, Peter Veentjer wrote:
>
> How expensive is a volatile read for implementing a single writer 
> performance counter?
>
> One can easily create some kind of performance counter using an AtomicLong 
> or using a LongAdder if there is contention. 
>
> some example code:
>
> public class Counter {
>
>     private final AtomicLong c = new AtomicLong();
>  
>     public void inc(){
>         c.addAndGet(1);
>     }
>
>     public long get(){
>         return c.get();
>     }
> }
>
> But in some cases one can create a counter where there is only a single 
> writer and multiple readers. In these case one can make use of 
> AtomicLong.lazySet. This prevent the cpu to wait for the store buffer to be 
> drained. Martin Thompson explained this in his excellent training.
>
> So you get something like this:
>
> public class Counter {
>
>     private final AtomicLong c = new AtomicLong();
>
>     public void inc(){
>         long newValue = c.get()+1;
>         c.lazySet(newValue);
>     }
>
>     public long get(){
>         return c.get();
>     }
> }
>
> But in this case you still need to do a volatile read to read the actual 
> value. In theory one could optimize this to:
>
> public class Counter {
>
>     private final AtomicLong c = new AtomicLong();
>     private long local;
>
>     public void inc(){
>         long newValue = local+1;
>         this.local = newValue;
>         c.lazySet(newValue);
>     }
>
>     public long get(){
>         return c.get();
>     }
> }
>
> In this case there is no volatile read involved, however more data needs 
> to be written to memory.
>
> As soon as I have time, I'll create a JMH benchmark. But I'm interested in 
> the thoughts behind volatile reads in this particular case. 
>

-- 
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.

Reply via email to