javamultithreadingatomicatomicinteger

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


I've read in Oracle docs that:

  • Reads and writes are atomic for reference variables and for most
    primitive variables (all types except long and double).

(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)

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


Solution

  • 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.