在没有Actors的Scala中同时变换HashMap

ade*_*rtc 1 concurrency scala parallel-collections

我想要做的是开始使用a的一些实现Map并通过迭代并行集合将数据累积到其中.密钥可以在线程之间"重叠",因为密钥是以概率方式生成的(与随机数生成有关).

防爆.线程1想要将key = A value = 1添加到地图中.如果它已经存在,则将1添加到现有值(因为值为1) - 如果不存在,则创建映射.同时,另一个线程有key = A和value = 2,并且想要做同样的事情.

有没有办法在不创建整个Actor系统的情况下做到这一点?

ConcurrentHashMap 来自Java的库似乎看起来很有趣,但是"弱一致"的迭代器让我感到困扰的是跨线程更新地图的安全性.

Vik*_*ang 7

没有Actors,这是一件非常重要的事情.

class CountMap[K <: AnyRef](mapSize: Int = 16) extends ConcurrentHashMap[K, AtomicLong](mapSize) {
  def addCount(key: K): Long = (get(key) match { // Check value for key
    case null =>  // If not mapped yet
      val al = new AtomicLong(0) // Create a new memory slot to keep the count in that is thread safe
      putIfAbsent(key, al) match { // Try to put our memory slot in atomically
        case null => al // If we succeeded then our memory slot should be used
        case some => some // if there already was a memory slot, use that one
      }
    case some => some // If there already was a memory slot, use that one
    }).incrementAndGet() // increment and get the current value of the slot associated with the given key

  def getCount(key: K): Long = get(key) match { // get the memory slot associated with the key
    case null => 0L // if none, say it's 0
    case some => some.get() // if some get its value
  }
}
Run Code Online (Sandbox Code Playgroud)