I'm trying to use an AtomicInteger variable as lock. So, wondering if the code posted below is thread safe. I know incrementAndGet() is an atomic operation. But, I'm not sure if the subsequent '==' operation will be atomic as well (what if the value gets incremented to 2, by the time I make the comparison.). So posting this question to hear your thoughts.
private AtomicInteger count = new AtomicInteger(0); //Shared variable
private final int max = 1;
if(count.incrementAndGet() == max) {
//Do something
}
Since
incrementAndGet()is an atomic operation, at most one thread will get1for result (as long as the AtomicInteger is not set to a value lower than 1). This is guaranteed by AtomicInteger. Although the actual comparison is not part of this atomic operation, only the thread which received1will run into theifblock. That's because the comparison compares two values of typeint: the result ofincrementAndGet()) andmax. The AtomicInteger doesn't play a role in it since the primitiveintdoesn't change it's value when the inner state ofcountchanges. tl;dr: Your code is equivalent to:Java provides many other ways to achieve thread-safety (Lock, CountDownLatch, Semaphore, ...), but since you are referring to an AtomicInteger, I believe AtomicInteger.compareAndSet() is more accurate to what you were asking: