加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Scala中使用ConcurrentLinkedQueue?

发布时间:2020-12-16 09:58:17 所属栏目:安全 来源:网络整理
导读:val nodes = Array.fill[mutable.Buffer[Int]](numNodes){new ArrayBuffer[Int]() with mutable.SynchronizedBuffer[Int]}def addMutualEdge(i: Int)(j: Int) {nodes(i) += j; nodes(j) += i} 当我编译它时,我得到弃用警告: SynchronizedBuffer is deprecat
val nodes = Array.fill[mutable.Buffer[Int]](numNodes){new ArrayBuffer[Int]() with mutable.SynchronizedBuffer[Int]}

def addMutualEdge(i: Int)(j: Int) {nodes(i) += j; nodes(j) += i}

当我编译它时,我得到弃用警告:

SynchronizedBuffer is deprecated. Synchronization via traits is deprecated as it is inherently reliable. Consider java.util.concurrent.ConcurrentLinkedQueue as an alternative

如何在上面的代码中使用java库?

解决方法

您可以使用ConcurrentLinkedQueue而不是Buffer,因为它也是可变的:

scala> import java.util.concurrent._
import java.util.concurrent._

scala> val nodes = Array.fill(10){new ConcurrentLinkedQueue[Int]()}
nodes: Array[java.util.concurrent.ConcurrentLinkedQueue[Int]] = Array([],[],[])

scala> def addMutualEdge(i: Int)(j: Int) {nodes(i).add(j); nodes(j).add(i)}
addMutualEdge: (i: Int)(j: Int)Unit

它是最快的选项,因为此队列基于CAS操作,因此没有阻塞(与SynchronizedBuffer相比).另一种选择是直接同步操作:

scala> val nodes = Array.fill[mutable.Buffer[Int]](10){new ArrayBuffer[Int]()}
nodes: Array[scala.collection.mutable.Buffer[Int]] = Array(ArrayBuffer(),ArrayBuffer(),ArrayBuffer())

scala> def addMutualEdge(i: Int)(j: Int) = this.synchronized{nodes(i) += j; nodes(j) += i}
addMutualEdge: (i: Int)(j: Int)scala.collection.mutable.Buffer[Int]

您还可以将java的Collections.synchronizedList(…)与scala.collection.JavaConverters.asScala结合使用

import java.util._
import scala.collection.JavaConverters._
scala> val nodes = Array.fill(10){Collections.synchronizedList(new ArrayBuffer[Int]().asJava).asScala}
nodes: Array[scala.collection.mutable.Buffer[Int]] = Array(Buffer(),Buffer(),Buffer())

或者您可以使用AtomicReferenceArray:

implicit class RichAtomic[T](a: AtomicReferenceArray[List[T]]) { def apply(i: Int) = (a,i); def update(i: Int,e: List[T]) = a.set(i,e)}
implicit class RichList[T](a: (AtomicReferenceArray[List[T]],Int)) { def ::=(e: T) = while({val lst = a._1.get(a._2);!a._1.compareAndSet(a._2,lst,e :: lst)}){}}
implicit def toList[T](a: (AtomicReferenceArray[List[T]],Int)) = a._1.get(a._2)

val nodes = new AtomicReferenceArray(Array.fill[List[Int]](10){Nil})

scala> def addMutualEdge(i: Int)(j: Int) = {nodes(i) ::= j; nodes(j) ::= i}
addMutualEdge: (i: Int)(j: Int)Unit

Implicits用于提供simillar接口,就像Array一样.注意,:: =将元素添加到列表的开头.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读