多线程自动求和大量值 [英] Multithreading summing large number of values atomically

查看:209
本文介绍了多线程自动求和大量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,其中我们有大量线程,并且必须原子地添加100的值.我使用的AtomicLong效果很好,但仍然需要提高性能.有什么可以提供比AtomicLong更好的性能的吗?

I am developing an application where we have large number of threads and have to add 100's of values atomically. I am using AtomicLong which work well but still need to improve the performance. Is there something which offers better performance then AtomicLong?

推荐答案

您可以使用LongAdder . LongAdder提供了比AtomicLong更好的性能.我建议阅读这篇文章,其中作者发布了基准测试结果并解释了退出有关LongAdder性能的许多细节.概括地说,LongAdder扩展了Striped64,它通过使用单元格的哈希表很好地处理了竞争退出.因此,当2个线程尝试放置值时,则很有可能两个线程都将结束在不同单元格中放置值.单元类使用填充策略来减少CPU缓存的分配.此外,如果您查看源代码,那么您会发现单元格类使用CAS.

You can use LongAdder. LongAdder offer much better performance then AtomicLong. I would suggest reading this article where the author published benchmarking results and explained quit many details regarding LongAdder performance. But in a nutshell LongAdder extends Striped64 that handles contentation quit well by using hash table of cells. So when 2 threads try to put some value ,then there is good probability that both of them will end putting value in different cells. Cell class uses Padding stratergy to reduce CPU cache contentation. Moreover if you take a look on source code then you will find that cell class uses CAS.

Unsafe.compareAndSwap操作是原子的.他们将指针指向 内存块(在这种情况下,由this和valueOffset组成) 一起指向值),比较值和交换值.如果JVM 发现所寻址的内存的值等于比较的值 值,然后将交换值存储在寻址的内存中,并且 返回true.这意味着CAS操作既快速又线程 更新变量值并获得有关是否进行反馈的安全方法 操作成功或是否存在争用.

Unsafe.compareAndSwap operations are atomic. They take a pointer to a chunk of memory (in this case comprised of this and valueOffset which together point to value), a compare value and a swap value. If the JVM finds that the value of the addressed memory is equal to the compare value, then it stores the swap value in the addressed memory and returns true. This means that CAS operations are a fast and thread safe way to update the value of a variable and get feedback on whether the operation was successful or whether there was contention.

这篇关于多线程自动求和大量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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