简体   繁体   中英

Why do we need Atomic* classes if wrapper classes are already immutable?

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 .

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.

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.

你有没有想过当我有一个Integer(1) ,我怎么能把它改成Integer(2) ,整数是不可变的。所以我需要创建一个新的并设置它的值,但这个过程不是原子的。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM