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

Function method to get previous value and new value from ConcurrentHashMap

王林
Release: 2024-02-08 22:40:37
forward
947 people have browsed it

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)
  }
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template