Lah*_*iru 5 concurrency scala data-structures
我PriorityQueue在多个线程中使用 a 。我不确定它是线程安全的数据结构。
scala.collection.mutable.PriorityQueue跨多个线程使用是否安全?
TL;DR:这不安全。
我们来看一下!scala.collection.mutable.PriorityQueue使用
private val resarr = new ResizableArrayAccess[A]
Run Code Online (Sandbox Code Playgroud)
其中 ResizingArrayAccess在 PriorityQueue 中定义为
private class ResizableArrayAccess[A] extends AbstractSeq[A] with ResizableArray[A] with Serializable {
Run Code Online (Sandbox Code Playgroud)
从那里,转到scala.collection.mutable.ResizableArray,很明显这不是线程安全的,例如通过查看update方法:
protected var array: Array[AnyRef] = new Array[AnyRef](math.max(initialSize, 1))
// ... snip ... //
def update(idx: Int, elem: A) {
if (idx >= size0) throw new IndexOutOfBoundsException(idx.toString)
array(idx) = elem.asInstanceOf[AnyRef]
}
Run Code Online (Sandbox Code Playgroud)
因此,我们对可变变量的访问不受保护,并且scala.collection.mutable.PriorityQueue不鼓励从多个线程使用。
如果您确实需要从多个线程使用它并且并发性并不重要,您可以使用同步的某些含义,例如scala.util.SyncVar防止竞争条件等并发问题。否则使用其他数据结构会更好。