1

I have a program running multi-thread, all thread share and process on single AtomicLong variable. Each of them will call getAndAdd() method first to retrieve value and process further.

If all threads running simultaneously, does calling above method cause one thread to waiting another thread to finish getting value?

Thong Vo
  • 809
  • 1
  • 9
  • 21

1 Answers1

3

The threads are not waiting (in the sense of Object::wait), they are looping until they succeed in getting and adding to the AtomicLong.

For reference, the code in JDK 8 looks like this:

public final long getAndAddLong(Object o, long offset, long delta) {
  long v;
  do {
    v = getLongVolatile(o, offset);
  } while (!compareAndSwapLong(o, offset, v, v + delta));
  return v;
}

Note that the method may be intrinsic (i.e. it is replaced at runtime by something more efficient, typically a single CPU instruction)

assylias
  • 321,522
  • 82
  • 660
  • 783
  • They are looping, you mean they will do nothing until they get the value? I was wondering does it impact the performance? – Thong Vo Jan 06 '17 at 09:20
  • They won't do nothing, they will loop (busy-waiting) so they will use 100% cpu. But that won't last long under normal contention conditions. If course, if your program has thousands of threads doing nothing but `getAndAdd`ing you will notice a high CPU usage, but that's an unrealistic scenario. – assylias Jan 06 '17 at 09:49
  • See also: http://stackoverflow.com/questions/2664172/java-concurrency-cas-vs-locking – assylias Jan 06 '17 at 09:49