Is AtomicInteger honest?

Does AtomicInteger provide a guarantee of fairness? for example, the order of thread execution in the first place? An animated example in Victor Grazi, a parallel animated one , definitely does not demonstrate such justice. I searched and found nothing convincing.

+3
source share
3 answers

No, there is no such guarantee. If he was alone, this will be indicated in the documentation.

When you think about it, it AtomicIntegeris basically a thin shell compare-and-swap (or similar). To guarantee the semantics of the first trick, synchronization between threads is required, which is expensive and runs counter to the idea itself AtomicInteger.

What happens is that if there are several threads that want, say, incrementAndGet()the same atomic integer at the same time, the order in which they finish the race is not indicated.

+6
source

It costs nothing that his work is very fast compared to anything else that you are likely to do. This means that you are unlikely to get competition, so justice is unlikely to be a problem.

2 ( ), . , AtomicLong.

+3

If you look at the source, you will receive the correct answer, which is YES and NO about ordering guarantees. It depends on which method is being called. Some support warranties are ordered and some are not.

The following source shows that it supports both modes depending on which method is called.

  138       /**
  139        * Atomically sets the value to the given updated value
  140        * if the current value {@code ==} the expected value.
  141        *
  142        * <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
  143        * and does not provide ordering guarantees, so is only rarely an
  144        * appropriate alternative to {@code compareAndSet}.
  145        *
  146        * @param expect the expected value
  147        * @param update the new value
  148        * @return true if successful.
  149        */
  150       public final boolean weakCompareAndSet(int expect, int update) {
  151           return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
  152       }

If in doubt, read the JavaDoc, and if still unclear, read the source.

+1
source

All Articles