私のクラスはConcurrentHashmap[String、immutable.List[String]]から拡張されています
そしてそれは2つの方法があります:
def addEntry(key: String, newList: immutable.List[String]) = {
...
//if key exist,appending the newList to the exist one
//otherwise set the newList as the value
}
def resetEntry(key: String): Unit = {
this.remove(key)
}
addEntryメソッドのスレッドを安全にするために、私は試しました:
this.get(key).synchronized{
//append or set here
}
ただし、キーが存在しない場合はnullポインター例外が発生し、同期前にputIfAbsent(key、new immutable.List())を使用すると、putIfAbsentの後、同期ブロックに入る前にキーが機能しなくなります。キーはresetEntryによって削除される場合があります。
addEntryとresetEntryの両方の同期メソッドは機能しますが、ロックが大きすぎます
だから、私は何ができますか?
ps。この投稿は、ConcurrentHashMapスレッド内のBigDecimalの更新を安全にする方法と類似していますが、plzは、一般的なガイド以外のコーディング方法を理解するのに役立ちます
--update-- checkout https://stackoverflow.com/a/34309186/404145、ほぼ3年以上後にこれを解決しました。