0

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

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
ivenhov
  • 311
  • 3
  • 12
  • This sounds like a very weird approach not to say very wrong, why do you need to do this? Do you have a perf issue in your application that is related to this? – Nicolas Filotto Aug 03 '16 at 11:59
  • So it's not an issue for you if reader reads an old value? – Kayaman Aug 03 '16 at 12:11
  • No, it's not an issue as long as at some point 10ms etc I will get correct result i.e. val == visibleCounter – ivenhov Aug 03 '16 at 12:21
  • @Nicolas. Thread that is doing write is in a critical path and I would like to avoid any slowdown if possible – ivenhov Aug 03 '16 at 12:23

1 Answers1

1

If lazy increment is one of your options I'll suggest LongAdder. link LongAdder is good for multiple threads updates.

... under high contention, expected throughput of this class is significantly higher (than AtomicLong)

Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27
  • I should have mentioned. I'm still on Java 1.7 and I'm not sure if updating Long would be more performant than int – ivenhov Aug 03 '16 at 12:19