Why is AtomicInteger needed if writes and reads to int variables are atomic? Why is AtomicInteger needed if writes and reads to int variables are atomic? multithreading multithreading

Why is AtomicInteger needed if writes and reads to int variables are atomic?


While a single store to or a single load from an ordinary int is atomic in Java, you cannot atomically, say, increment it. Doing so would require you to first load the value, then compute the new value depending on it and then store the new value back. But between the two accesses, another thread might have modified the value. AtomicInteger provides operations like getAndIncrement that can be used for this purpose without having to use a lock.


Deprecated? Not at all. While individual reads and writes of primitive variables are atomic, AtomicInteger (and the other atomic classes in java.util.concurrent.atomic) provides more complex operations that are also atomic. These include things like addAndGet(int), which are not at all atomic for primitive int variables. Thus,

int i = 3;AtomicInteger j = new AtomicInteger(3);i += 5; // NOT thread-safe -- might not set i to 8int n = j.addAndGet(5); // thread-safe -- always sets n to 8

(Both of the comments above are under the assumption that i and j are not changed by the time the statement in question starts executing, but might be changed by another thread after execution starts but before it is finished.)


Does it mean that AtomicInteger is deprecated and shouldn't be used in new projects?

No. First and most obvious, if it were deprecated, it would be marked as such.

Furthermore, AtomicInteger and primitive int simply aren't interchangeable. There are a lot of differences, but here are the first three that spring to mind:

  • AtomicInteger can be passed by reference, unlike primitive int, which is passed by value.
  • AtomicInteger has a some operations, such as compareAndSet(), that are unavailable on primitives.
  • Even those that superficially look the same, namely AtomicInteger.getAndIncrement() vs. int++ are different; the former is atomic, the second is two operations that are not atomic together.

I guess this feature has been added in some new JDK release because I used to think that reads/writes of ALL primitive variables are NOT atomic

Reads and writes of primitives of 32-bits or smaller have always been atomic.