When return value is of interest, is it possible that in case of AtomicInteger.getAndIncrement()
, two threads who call this method will get the same value?
In case of AtomicInteger.incrementAndGet()
it makes sense two threads will get different value because of the increment happening first.
Both getAndIncrement
and incrementAndGet
methods guarantee uniqueness of return value.
One may think as following relation between these two methods ( a
- variable of AtomicInteger
class):
a.IncrementAndGet() == a.getAndIncrement() + 1
See also https://stackoverflow.com/a/15137349/3440745 about actual implementation of these methods.
Both incrementAndGet
and getAndIncrement
meet your requirement since they will
Atomically adds the given value to the current value.
Difference is:
incrementAndGet
return updated value
getAndIncrement
return current value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.