gpt4 book ai didi

java - Scala:如何测试 mutable.Set 的并发性

转载 作者:行者123 更新时间:2023-11-30 10:04:11 25 4
gpt4 key购买 nike

在 Scala 中,并发和非并发 Set 具有完全相同的类型:

import collection.JavaConverters._

// A regular Set in Scala, not concurrent.
val regularSet: mutable.Set[Int] = mutable.Set[Int]()

// A concurrent set. It has the same type as a regular set, but underneath, it is actually concurrent. In my opinion, this is a flaw in the type system for Scala collections
val concurrentSet: mutable.Set[Int] = java.util.concurrent.ConcurrentHashMap.newKeySet[Int]().asScala

我想要一种方法来实际测试一个集合是否并发。

最佳答案

回答

您可以通过创建许多尝试从共享 mutable.Set 中添加/删除相同元素的线程来凭经验测试它

import java.util.concurrent.{Callable, ExecutorService, Executors}
import scala.collection.mutable

def testSet(set: mutable.Set[Int]) {
val e: ExecutorService = Executors.newFixedThreadPool(5)
val tasks = for (i <- 0 to 50000) yield {
e.submit(new Callable[Unit]() {
override def call() {
for (j <- 0 to 10) {
set.add(i + j)

// This will throw a Null Pointer Exception for the non-concurrent version
// This is because it is trying to remove something that another thread already removed.
set.remove(i + j)
}
}
})
}
for (result <- tasks) result.get()
e.shutdown()
}

// Can't check the type! They have the same type.
val regularSet: mutable.Set[Int] = mutable.Set[Int]()
val concurrentSet: mutable.Set[Int] = java.util.concurrent.ConcurrentHashMap.newKeySet[Int]().asScala

testSet(concurrentSet) // Success!
testSet(regularSet) // FAILS! Almost always throws a NullPointerException on my system.

限制

运行测试将需要系统资源,例如线程和 CPU 时间。在运行时在生产环境中运行它并不合适。

这不是演绎证明。由于竞争条件是随机的,因此测试将非并发对象分类为并发的可能性很小。但是,运行测试的时间更长会导致检测到非并发对象的概率接近确定性。

附加评论

理想情况下,会有一种方法可以使用反射和类型系统来查看底层对象是什么,并测试它是否是 ConcurrentHashMap(我认为这是 Scala 的主要缺陷,因为一些运行多线程任务的函数不能有效阻止函数调用者传入非并发对象)。

但这至少提供了一种检验它的经验方法。

致谢

How can I test that ConcurrentHashMap is truly thread-safe? 中提出了类似的问题.我修改了它以使用 Sets:

推荐

我建议使用 concurrent.Map[T, Unit] 而不是 mutable.Set[T]。原因是您将能够利用类型系统以 100% 的信心确保您的函数/类操作的对象实际上是并发的。

是的,您将失去 Set 语义,例如 .add(setMember) 方法。但你会获得安全。

如果您坚持使用并发 mutable.Set,请考虑制作一个包装类容器,以防止意外初始化为非并发 mutable.Set

关于java - Scala:如何测试 mutable.Set 的并发性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56013503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com