Does getAndAdd method in AtomicLong cause threads waiting?

207 views Asked by At

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?

1

There are 1 answers

3
assylias On

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)