I have a situation where one thread updates int and another one at some point reads it. So single-reader single-writer.
So far I was using volatile
int for that purpose, but since this forces full sync on memory barriers I was thinking about something else.
One approach would be AtomicInteger.incrementAndGet()
but I think this has exactly the same effect and will actually be slower
Another approach would be to use AtomicInteger.lazySet
with extra non-volatile counter for writer.
So basically we would have
private int counter;
public AtomicInteger visibleCounter = new AtomicInteger();
private void write() {
counter++
visibleCounter.lazySet(counter)
}
// called by reader
public int isCountEqual(int val) {
return val == visibleCounter.get()
}
as a naive "lazyIncrement
".
Would it be actually more performant than simple increment of volatile
int by writer?
Thanks