[英]Why do we need Atomic* classes if wrapper classes are already immutable?
I recently encountered atomic classes from java.util.concurrent.atomic package. 我最近遇到了java.util.concurrent.atomic包中的原子类。 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.
后来我才知道Integer,Boolean,Character等包装类本质上是不可变的,为什么我们需要像AtomicInteger或AtomicLong这样的Atomic *类。 Also, please explain what is AtomicReference .
另外,请解释什么是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 . Atomic*
类的真正优势在于它们公开了一种原子比较和交换方法,这对于实现无锁算法非常有用。
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. 这是一个关于
compareAndSet
原理的一个很好的问题。
From documentation: 来自文档:
Reading about atomic / volatile / synchronized will help you to maintain the difference between them. 阅读atomic / volatile / synchronized将帮助您保持它们之间的差异。
你有没有想过当我有一个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.
java.util.concurrent.atomic包为我们做了。 Wrapper classes are immutable, we can't modify it, need to create a new instance.
包装类是不可变的,我们无法修改它,需要创建一个新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.