-
Notifications
You must be signed in to change notification settings - Fork 337
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improvement: Add atomix update on TrieMap
- Loading branch information
Showing
2 changed files
with
69 additions
and
21 deletions.
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
mtags/src/main/scala/scala/meta/internal/mtags/AtomicTrieMap.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package scala.meta.internal.mtags | ||
|
||
import java.util.concurrent.ConcurrentHashMap | ||
|
||
import scala.collection.concurrent.TrieMap | ||
|
||
/** | ||
* This class is a wrapper around TrieMap that provides atomic updateWith | ||
*/ | ||
final class AtomicTrieMap[K, V] { | ||
private val trieMap = new TrieMap[K, V]() | ||
private val concurrentMap = new ConcurrentHashMap[K, V] | ||
|
||
def get(key: K): Option[V] = trieMap.get(key) | ||
|
||
def contains(key: K): Boolean = trieMap.contains(key) | ||
|
||
def updateWith(key: K)(remappingFunc: Option[V] => Option[V]): Unit = { | ||
val computeFunction = new java.util.function.BiFunction[K, V, V] { | ||
override def apply(k: K, v: V): V = { | ||
trieMap.get(key) match { | ||
case Some(value) => | ||
remappingFunc(Some(value)) match { | ||
case Some(newValue) => | ||
trieMap.update(key, newValue) | ||
case None => | ||
trieMap.remove(key) | ||
} | ||
case None => | ||
remappingFunc(None).foreach(trieMap.update(key, _)) | ||
} | ||
null.asInstanceOf[V] | ||
} | ||
} | ||
concurrentMap.compute(key, computeFunction) | ||
} | ||
} | ||
|
||
object AtomicTrieMap { | ||
def empty[K, V]: AtomicTrieMap[K, V] = new AtomicTrieMap[K, V] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters