0

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.

xingbin
  • 27,410
  • 9
  • 53
  • 103
ffff
  • 2,853
  • 1
  • 25
  • 44
  • If I truly want a way to get incremental numbers in a multi threaded environment, should I prefer `AtomicInteger.incrementAndGet()` over `AtomicInteger.getAndIncrement()` – ffff Jul 18 '18 at 12:44

2 Answers2

0

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.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
0

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

Community
  • 1
  • 1
xingbin
  • 27,410
  • 9
  • 53
  • 103