Home >Java >Function method to get previous value and new value from ConcurrentHashMap

Function method to get previous value and new value from ConcurrentHashMap

王林
王林forward
2024-02-08 22:40:37930browse

php editor Youzi will introduce to you this time the function method of obtaining the previous value and new value in ConcurrentHashMap. ConcurrentHashMap is a thread-safe hash table implementation commonly used in Java concurrent programming. It provides some convenient function methods for operating key-value pairs in the hash table. It includes function methods to obtain the previous value and the new value. Through these methods, the value corresponding to the key in the hash table can be operated and updated. Next, we will introduce the usage and precautions of these function methods in detail.

Question content

I need to get previous value and new value from java concurrenthashmap (in scala code). To keep it thread safe I use compute block which only returns the new value. Is it possible to get both the new value and the previous value without using a var with an initial null ? Here is my current solution:

map: ConcurrentHashMap[String, Object] = new ConcurrentHashMap

  def foo = {
    var previousValue: Object = null

    val newValue = map.compute("key", (_, value) => {
      previousValue = Option(value).getOrElse(initialValue)
      setNewValue(previousValue)
     }
    )

    (previousValue, newValue)
  }

Solution

No. The current version of ConcurrentHashMap.

The above is the detailed content of Function method to get previous value and new value from ConcurrentHashMap. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete