如果没有 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
}
}