ConcurrentMultiMap 实现

news/2024/7/3 1:07:58

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

Index,akka用来存储对应dispatcher和actor的,也是Akka实现的`ConcurrentMultiMap<K,V>`

`key`类型自定义,`value`是由`ConcurrentSkipListSet`构成的,内部其实就对`ConcurrentMultiMap<K, ConcurrentSkipListSet<V>>`的再封装

而Index的`mapSize`参数对应`ConcurrentHashMap`的 `initialCapacity`, 语义都变味了!

读取时会copy(asScala)一份,并返回

/**
 * Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
 */
package akka.util

import annotation.tailrec

import java.util.concurrent.{ ConcurrentSkipListSet, ConcurrentHashMap }
import java.util.Comparator
import scala.collection.JavaConverters.{ asScalaIteratorConverter, collectionAsScalaIterableConverter }
import scala.collection.mutable

/**
 * An implementation of a ConcurrentMultiMap
 * Adds/remove is serialized over the specified key
 * Reads are fully concurrent <-- el-cheapo
 */
class Index[K, V](val mapSize: Int, val valueComparator: Comparator[V]) {//valueComparator

  def this(mapSize: Int, cmp: (V, V) ⇒ Int) = this(mapSize, new Comparator[V] {
    def compare(a: V, b: V): Int = cmp(a, b)
  })
  
  //java集合
  private val container = new ConcurrentHashMap[K, ConcurrentSkipListSet[V]](mapSize)
  private val emptySet = new ConcurrentSkipListSet[V]//线程安全集合

  /**
   * Associates the value of type V with the key of type K
   * @return true if the value didn't exist for the key previously, and false otherwise
   */
  def put(key: K, value: V): Boolean = {
    //Tailrecursive spin-locking put
    @tailrec
    def spinPut(k: K, v: V): Boolean = {//
      var retry = false
      var added = false
      val set = container get k

      if (set ne null) {
        set.synchronized {//删除的时候有synchronized,但是上一句ne null判定时没有被锁定,
          if (set.isEmpty) retry = true //IF the set is empty then it has been removed, so signal retry//当为empty的时候,说明它已经不在container中,正在被删除中...
          else { //Else add the value to the set and signal that retry is not needed
            added = set add v
            retry = false
          }
        }
      } else {//
        val newSet = new ConcurrentSkipListSet[V](valueComparator)
        newSet add v

        // Parry for two simultaneous putIfAbsent(id,newSet)
        val oldSet = container.putIfAbsent(k, newSet)//插入的时候,通过putIfAbsent,防止覆盖
        if (oldSet ne null) {
          oldSet.synchronized {
            if (oldSet.isEmpty) retry = true //IF the set is empty then it has been removed, so signal retry
            else { //Else try to add the value to the set and signal that retry is not needed
              added = oldSet add v
              retry = false
            }
          }
        } else added = true
      }

      if (retry) spinPut(k, v)
      else added
    }

    spinPut(key, value)
  }

  /**
   * @return Some(value) for the first matching value where the supplied function returns true for the given key,
   * if no matches it returns None
   */
  def findValue(key: K)(f: (V) ⇒ Boolean): Option[V] =
    container get key match {
      case null ⇒ None
      case set  ⇒ set.iterator.asScala find f
    }

  /**
   * Returns an Iterator of V containing the values for the supplied key, or an empty iterator if the key doesn't exist
   */
  def valueIterator(key: K): scala.Iterator[V] = {
    container.get(key) match {
      case null ⇒ Iterator.empty
      case some ⇒ some.iterator.asScala
    }
  }

  /**
   * Applies the supplied function to all keys and their values
   */
  def foreach(fun: (K, V) ⇒ Unit): Unit =
    container.entrySet.iterator.asScala foreach { e ⇒ e.getValue.iterator.asScala.foreach(fun(e.getKey, _)) }

  /**
   * Returns the union of all value sets.
   */
  def values: Set[V] = {
    val builder = Set.newBuilder[V]
    for {
      values ← container.values.iterator.asScala
      v ← values.iterator.asScala
    } builder += v
    builder.result()
  }

  /**
   * Returns the key set.
   */
  def keys: Iterable[K] = container.keySet.asScala

  /**
   * Disassociates the value of type V from the key of type K
   * @return true if the value was disassociated from the key and false if it wasn't previously associated with the key
   */
  def remove(key: K, value: V): Boolean = {
    val set = container get key

    if (set ne null) {
      set.synchronized {
        if (set.remove(value)) { //If we can remove the value
          if (set.isEmpty) //and the set becomes empty
            container.remove(key, emptySet) //We try to remove the key if it's mapped to an empty set

          true //Remove succeeded
        } else false //Remove failed
      }
    } else false //Remove failed
  }

  /**
   * Disassociates all the values for the specified key
   * @return None if the key wasn't associated at all, or Some(scala.Iterable[V]) if it was associated
   */
  def remove(key: K): Option[Iterable[V]] = {
    val set = container get key

    if (set ne null) {
      set.synchronized {
        container.remove(key, set)
        val ret = collectionAsScalaIterableConverter(set.clone()).asScala // Make copy since we need to clear the original
        set.clear() // Clear the original set to signal to any pending writers that there was a conflict
        Some(ret)
      }
    } else None //Remove failed
  }

  /**
   * Removes the specified value from all keys
   */
  def removeValue(value: V): Unit = {
    val i = container.entrySet().iterator()
    while (i.hasNext) {
      val e = i.next()
      val set = e.getValue()

      if (set ne null) {
        set.synchronized {
          if (set.remove(value)) { //If we can remove the value
            if (set.isEmpty) //and the set becomes empty
              container.remove(e.getKey, emptySet) //We try to remove the key if it's mapped to an empty set //类似 compareAndSwap
          }
        }
      }
    }
  }

  /**
   * @return true if the underlying containers is empty, may report false negatives when the last remove is underway
   */
  def isEmpty: Boolean = container.isEmpty

  /**
   *  Removes all keys and all values
   */
  def clear(): Unit = {
    val i = container.entrySet().iterator()
    while (i.hasNext) {
      val e = i.next()
      val set = e.getValue()
      if (set ne null) { set.synchronized { set.clear(); container.remove(e.getKey, emptySet) } }
    }
  }
}

/**
 * An implementation of a ConcurrentMultiMap
 * Adds/remove is serialized over the specified key
 * Reads are fully concurrent <-- el-cheapo
 */
class ConcurrentMultiMap[K, V](mapSize: Int, valueComparator: Comparator[V]) extends Index[K, V](mapSize, valueComparator)


转载于:https://my.oschina.net/myprogworld/blog/381179


http://www.niftyadmin.cn/n/2828932.html

相关文章

GPS机制分析(5)

1. 概述 ​ 上面的几篇文章论述了gps的打开启动初始化等动作,万事俱备只欠东风了。这一系列文章主要讲的是Position信息如何从modem层传递到loc eng层最后一直到Java上层的。由于loc eng层到modem层是属于消息触发的&#xff0c;也就是说正常的流程是&#xff1a;modem层传上来…

GPS机制分析(6)

7. gps数据从HAL传输到Java ​ 上面UlpLocation类型的mLocation作为参数传入&#xff0c;这里传递的还是UlpLocation类型的数据&#xff0c;不是hal层使用的GpsLocation类型&#xff0c;因此我们看一下UlpLocation类型的数据转换成GpsLocation类型的数据的过程&#xff1a; h…

IPC—Android Binder (1)

IPC是Inter-Process Communication的缩写&#xff0c;含义就是跨进程通信。 多进程场景 WebView加载图片推送 原因 内存不够->内存就够了 App运行独立的虚拟机——每个进程分配运行内存是有限的——32M、64M、48M 加载一个大图片——直接OOM 如果一旦奔溃&#xff0c;…

AndroidGPS定位应用流程

AndroidGPS定位应用流程 这里先了解下应用层流程。 根据这个框架&#xff0c;GPS在应用层实现的最基本流程示例&#xff1a; public class MainActivity extends Activity {private LocationManager mLocationManager;Overrideprotected void onDestroy() {super.onDestroy…

怎么把照片做成消消乐_开心消消乐特效制作如何快速的消除过关

开心消消乐特效制作如何快速的消除过关。在闯关的时候&#xff0c;我们想要制作三星过关&#xff0c;特效的制作是我们必须的过程。如果没有特效帮助我们大量的消除&#xff0c;想要得到3星的分数是比较困难的。但是在释放特效的时候&#xff0c;我们是需要一定的技巧的。单独的…

debian卸载php_在 Ubuntu/Debian 下安装 PHP7.3 教程

介绍最近的 PHP 7.3.0 已经在 2018 年12月6日 发布 GA&#xff0c;大家已经可以开始第一时间体验新版本了&#xff0c;这里先放出 PHP7.3 安装的教程以便大家升级。适用系统&#xff1a; Ubuntu 18.04 LTS / Ubuntu 16.04 LTS &#xff0f; Ubuntu 14.04 LTS / Debian 9 stretc…

图解C/C++中函数参数的值传递、指针传递与引用传递

因为一直对这几种函数参数的传递方式理解的不是很透彻&#xff0c;花了一段时间仔细捋清了他们之间的区别。这个问题也是编程初级阶段会经常遇到的问题&#xff0c;也是有可能在面试中遇到的基本问题&#xff0c;在此进行了简单的总结一下&#xff0c;一是加深自己的理解&#…