I recently encountered atomic classes from java.util.concurrent.atomic package. As far as I know, immutable classes are by default thread safe by nature, so we do not need to synchronize them. Later I came to know that wrapper classes like Integer, Boolean, Character, etc are immutable by nature, so why do we need Atomic* classes like AtomicInteger or AtomicLong. Also, please explain what is AtomicReference.
-
7Atomic classes are **mutable**. – Eran Sep 14 '16 at 05:47
-
1Because ... maybe you want an atomic class that isn't immutable? – Dawood ibn Kareem Sep 14 '16 at 05:52
-
@Eran I agree, but wrapper classes will work in multithreaded environment, then why atomic class is required. Is David's reason the main reason they created them. – Shaggy Sep 14 '16 at 06:01
-
2With immutable classes alone, all you can share is constants. I think it doesn't take a lot of imagination to realize that sometimes you need more than constants. – Marko Topolnik Sep 14 '16 at 07:09
4 Answers
The atomic classes are mutable, but have strong memory consistency guarantees with regard to modifications. So they serve a different purpose from the immutable wrapper classes.
The real advantage of the Atomic*
classes is that they expose an atomic compare-and-swap method, which can be very useful for implementing lock-free algorithms.
Like many intermediate to advanced concurrency tools, if you can't imagine why you would need such a thing then you probably shouldn't try to use them. If you stick to immutability or explicit locking everywhere then you probably won't need atomics.

- 59,486
- 16
- 97
- 135
Here is a nice question about what the compareAndSet
principle.
From documentation:
- The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors.
Reading about atomic / volatile / synchronized will help you to maintain the difference between them.

- 1
- 1

- 10,019
- 9
- 74
- 96
Have you ever thought when I have an Integer(1)
,how can I change it to Integer(2)
,Integer is immutable.so I need create new one and set it value,but the process is not atomic.

- 5,669
- 9
- 46
- 84

- 63
- 5
Concept of atomicity comes when something is mutable. We want the operation of modifying a field/variable (could be many steps, read -> update -> write) as atomic operation. So that in multithreaded scenario, there should not be any data corruption. java.util.concurrent.atomic package does it for us. Wrapper classes are immutable, we can't modify it, need to create a new instance.

- 1