I have an application with a single writer thread which does some stuff and updates some metrics e.g. counters etc. The application has a number of other threads which read the stats and do stuff with them. It's not essential that the metrics are up to date but the writer thread needs to be blocked for as little time as possible. I was wondering which of the following would better suit my needs:
Option 1 - have a non atomic field that only the writer can update, and an AtomicXXX field which is set using lazySet
:
class Stats1
{
private final AtomicLong someCounterAtomic = new AtomicLong(0);
private long someCounter = 0;
// writer thread updates the stats using this
public void incrementCounter(long counterIncrement)
{
someCounter += counterIncrement;
someCounterAtomic.lazySet(someCounter);
}
// reader threads call this
public long getCounterValue()
{
return someCounterAtomic.get();
}
}
Option 2 - Just have an AtomicXXX field which is updated via addAndGet
:
class Stats2
{
private final AtomicLong someCounter = new AtomicLong(0);
// writer thread updates the stats using this
public void incrementCounter(long counterIncrement)
{
someCounter.addAndGet(counterIncrement);
}
// reader threads call this
public long getCounterValue()
{
return someCounter.get();
}
}
Or would I be better off doing something else?
Thanks in advance.