Java mapping concurrent update

I'm trying to create a map with int value and increase them through multiple threads Two or more threads may add the same key

The concurrenthashmap document is very unclear to me because it is:

Retrieval operations (including get) are generally not blocked, so they may overlap with update operations (including put and remove)

I want to know if the following code using concurrenthashmap works properly:

myMap. put(X,myMap.get(X)1);

If not, how can I manage such things?

Solution

Concurrent maps will not help your code thread safe You can also get the competition conditions:

Thread-1: x = 1,get(x)
Thread-2: x = 1,get(x)
Thread-1: put(x + 1) => 2
Thread-2: put(x + 1) => 2

Two increments occur, but you still get only 1 Concurrent maps are required only if you want to modify the map itself rather than its contents Even the simplest HashMap is threadsafe for concurrent reads, and the given map is no longer mutated

Therefore, you do not need to provide a thread - safe mapping for the original type, so you need a thread - safe wrapper for that type From Java util. concurrent. Anything in atomic, or if you need any type, scroll to your own locked container

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>