不安全的compareAndSwapInt与同步 [英] Unsafe compareAndSwapInt vs synchronize

查看:220
本文介绍了不安全的compareAndSwapInt与同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现几乎所有高级同步抽象(例如Semaphore,CountDownLatch,java.util.concurrent中的Exchanger)和并发集合都使用Unsafe中的方法(例如compareAndSwapInt方法)来定义关键部分。同时,我希望同步块或方法将用于此目的。
您能解释一下不安全的方法(我的意思是仅能原子设置值的方法)比同步更有效,为什么这样做呢?

I found that almost all high level synchronization abstractions(like Semaphore, CountDownLatch, Exchanger from java.util.concurrent) and concurrent collections are using methods from Unsafe(like compareAndSwapInt method) to define critical section. In the same time I expected that synchronize block or method will be used for this purpose. Could you explain is the Unsafe methods(I mean only methods that could atomically set a value) more efficient than synchronize and why it is so?

推荐答案

如果您希望等待很长时间(例如毫秒),则使用 synchronized 效率更高,因为线程可能会进入睡眠状态并释放线程。 CPU做其他工作。

Using synchronised is more efficient if you expect to be waiting a long time (e.g. milli-seconds) as the thread can fall asleep and release the CPU to do other work.

如果您希望操作很快完成,那么使用 compareAndSwap 效率更高。这是因为这是一条简单的机器代码指令,并且只需10 ns。但是,如果资源严重不足,该指令必须忙于等待,并且如果无法获取所需的值,它会忙于消耗CPU直到耗尽。

Using compareAndSwap is more efficient if you expect the operation to happen quite quickly. This is because it is a simple machine code instruction and take as little as 10 ns. However if a resources is heavily contented this instruction must busy wait and if it cannot obtain the value it needs, it can consume the CPU busily until it does.

如果使用利用堆外内存,您可以控制共享数据的布局,并避免错误共享(同一缓存行由多个CPU更新)。当您有多个值可能要独立更新时,这一点很重要。例如

If you use off heap memory, you can control the layout of the data being shared and avoid false sharing (where the same cache line is being updated by more than one CPU). This is important when you have multiple values you might want to update independently. e.g. for a ring buffer.

请注意,典型JVM的内部实现(例如,热点)通常将比较交换硬件指令用作 part synchronized 实现的(如果有这样的指令,例如x86),而另一个常见的替代方法是 LL / SC (例如POWER,ARM)。一种典型的策略,用于使快速路径使用比较和交换(或等效)尝试获取锁(如果锁是免费的),然后紧随其后的是简短的自旋循环,最后,如果失败则退回到操作系统级别的阻塞原语(例如, futex 事件)。细节远不止于此,还包括诸如偏向锁定和最终取决于实现。

Note that the internal implementation of a typical JVM (e.g., hotspot) will often used the compare-and-swap hardware instruction as part of the synchronized implementation if such an instruction is available (e.g,. x86), while the other common alternative is LL/SC (e.g., POWER, ARM). A typical strategy to for the fast path to use compare-and-swap (or equivalent) to attempt to obtain the lock if it is free, followed possibly by a short spin-loop and finally if that fails falling back to an OS-level blocking primitive (e.g., futex, Events). The details go far beyond this and include techniques such as biased locking and are ultimately implementation dependent.

这篇关于不安全的compareAndSwapInt与同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆