【问题标题】:ConcurrentHashMap parallelismThresholdConcurrentHashMap 并行度阈值
【发布时间】:2014-06-30 17:36:35
【问题描述】:
ConcurrentHashMap 有几个新方法。
我有两个关于他们的问题:
- 为什么不在
ConcurrentMap 中声明它们?
-
parallelismThreshold 到底是什么意思?
【问题讨论】:
标签:
java
parallel-processing
java-8
concurrenthashmap
【解决方案1】:
这些新方法似乎依赖于特定于 ConcurrentHashMap 的实现细节,但您必须从 Java 8 作者那里得到答案才能确定。 (他们确实会浏览)
-
来自 ConcurrentHashMap 的 Javadoc:
这些批量操作接受一个 parallelismThreshold 参数。如果估计当前地图大小小于给定阈值,则方法按顺序进行。使用 Long.MAX_VALUE 的值会抑制所有并行性。使用值 1 通过划分为足够多的子任务以充分利用用于所有并行计算的 ForkJoinPool.commonPool() 来实现最大并行度。通常,您首先会选择这些极端值之一,然后测量使用折衷开销与吞吐量的中间值的性能。
【解决方案2】:
parallelismThreshold 确定批量操作是按顺序执行还是并行执行。
并行运行有一些开销,因此它只有在某个地图大小阈值以上时才有用。
ConcurrentHashMaps 支持一组顺序和并行的批量
与大多数 Stream 方法不同的是,这些操作被设计为
安全且经常明智地应用,即使是正在使用的地图
由其他线程同时更新;例如,当计算一个
共享注册表中值的快照摘要。有三种
各种操作,每种有四种形式,接受函数有
键、值、条目和(键、值)参数和/或返回
价值观。因为 ConcurrentHashMap 的元素没有按顺序排列
任何特定的方式,并且可以在不同的顺序处理
不同的并行执行,提供函数的正确性
不应依赖于任何排序,或任何其他对象或值
在计算过程中可能会暂时改变;和
除了 forEach 动作,理想情况下应该没有副作用。大部分
Map.Entry 对象的操作不支持 setValue 方法。
- forEach: Perform a given action on each element. A variant form applies a given
transformation on each element before performing the action.
- search: Return the first available non-null result of applying a given function
on each element; skipping further search when a result is found.
- reduce: Accumulate each element. The supplied reduction function cannot rely on
ordering (more formally, it should be both associative and commutative).
There are five variants:
- Plain reductions. (There is not a form of this method for (key, value)
function arguments since there is no corresponding return type.)
- Mapped reductions that accumulate the results of a given function applied
to each element.
- Reductions to scalar doubles, longs, and ints, using a given basis value.
这些批量操作接受 parallelismThreshold 参数。方法
如果估计当前地图大小较小,则按顺序进行
超过给定的阈值。使用 Long.MAX_VALUE 的值会抑制
所有并行性。使用值 1 会导致最大并行度
划分为足够多的子任务以充分利用
ForkJoinPool.commonPool() 用于所有并行计算。
通常,您最初会选择这些极值之一,并且
然后衡量使用权衡取舍的中间值的性能
开销与吞吐量。
(Source)