Rohan Grover
Rohan Grover

Reputation: 1604

Is AtomicInteger fair?

Does AtomicInteger provide any kind of fairness guarantee? like first-come-first-serve execution order of threads on it? The animated example at Victor Grazi's concurrent animated definitely does not show any such fairness. I've searched and haven't found anything conclusive.

Upvotes: 3

Views: 409

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533472

Its worth nothing that its operation is very fast compared to anything else you are likely to do. This means you are highly unlikely to get contention so fairness is unlikely to be an issue.

If you call it 2 billion times (which you can do in seconds) it will over flow anyway. If this is a concern I would use AtomicLong.

Upvotes: 3

NPE
NPE

Reputation: 500187

No, there is no such guarantee. If there was one, it would be spelled out in the documentation.

When you think about it, AtomicInteger is basically a thin wrapper around compare-and-swap (or similar). Guaranteeing first-come-first-served semantics would require synchronization between threads, which is costly, and contrary to the very idea of AtomicInteger.

The way things are is that if there are multiple threads wanting to, say, incrementAndGet() the same atomic integer concurrently, the order in which they finish the race is unspecified.

Upvotes: 5

user177800
user177800

Reputation:

If you look at the source you will get the correct answer, which is YES and NO about ordering guarantees. It depends on which method is being called. Some support ordering guarantees, some don't.

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       }

When in doubt read the JavaDoc, and if still not clear read the source.

Upvotes: 1

Related Questions