英文:
Does AtomicInteger handle synchronization?
问题
如果两个线程都使用 i++ 增加同一个 int i
,会出现问题,因为 i++ 不是原子操作。这就是为什么有 AtomicInteger.increment()
,它可以使增加操作变为原子操作。因此,如果我们有1个核心和2个线程执行 .increment()
,就不会出现任何问题(因为它不会在操作过程中被挂起)。
但是如果我们有2个核心和2个线程,并且它们同时(完全相同的时间)调用那个 increment()
,会怎么样呢?
是否有可能它们加载同样的 int i
值?也就是说,如果 int i
是 1,最终结果将会是 2 而不是 3。在这种情况下,我们不关心它是否是原子操作,因为它们同时取得了相同的值。
底线是:AtomicInteger
是否处理了同步?
英文:
If two threads both increment same int i
using i++, we could get a problem, as i++ is not atomic operation. That is why there is AtomicInteger.increment()
, which makes incrementing atomic. So if we had 1 core and 2 threads doing .increment()
, there could be absolutely no problem (as it can't be suspended in the middle of operation).
But what if we had 2 cores and 2 threads and they parallelly (at exactly the same time) call that increment()
?
Could there be possibility that they load same value of int i
? Meaning if int i
was 1, end result would be 2 and not 3. In that case we don't care if it is atomic operation as they both took same value at the same time..
Bottom line: is synchronization handled by AtomicInteger?
答案1
得分: 3
> 有可能他们加载相同值的 int i
吗?
是的,有可能,但这已经为您处理好了。
incrementAndGet
方法使用了原子的“比较并设置”操作,该操作会设置增加后的值,但仅在尚未设置新值的情况下才会这样。如果比较失败,incrementAndGet
会获取新值然后重试。
总体效果是,多个线程可以安全地使用 incrementAndGet
。
英文:
> Could there be possibility that they load same value of int i
?
Yes, there is, but it's handled for you.
The incrementAndGet
method uses an atomic "compare and set" operation that sets the incremented value but only if a new value was not already set. If the compare fails, incrementAndGet
fetches the new value and tries again.
The net effect is, it is safe to use incrementAndGet
from multiple threads.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论