且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HashMap和并发 - 不同的键

更新时间:2023-09-19 17:37:22


我目前的实现是一种同步方法。这是否允许两个不同的线程同时将两个不同的键放入散列映射中?


否。只有一个 ConcurrentHashMap 或一个专门设计的并发映射可以安全地支持这个,所以你不可能同时把两个键从两个线程放到同一个映射中。


如何使两个不同的线程可以同时(同时)将不同的键放入哈希映射中?


blockquote>

如果不使用 ConcurrentHashMap ,另一个 ConcurrentMap 实现,或者实施你自己的。

Say I have a hash map and multiple threads. If I have a synchronized method that adds to the hash map, how would I make it possible that two different threads can put different keys simultaneously (concurrently) into the hash map?

My current implementation is a synchronized method. Would this allow two different threads to put two different keys simultaneously into the hash map?

I am using a regular hash map, not Java's concurrent hash map. I am not allowed to use a concurrent hash map.

EDIT: I think I found a solution! I think I may have miswrote this post. Let's say that the hash map is initialized as a Integer as its key and a LinkedList as its value. In order to put a totally new key, I realize that the whole hash map has to be synchronized (i.e. locked). However, if I am trying to add another String into an already contained key's corresponding LinkedList, I can just synchronize the hash map's get method. I think this will allow multiple threads to simultaneously (concurrently) add to the LinkedLists of different, already contained keys. Please let me know if I'm wrong.

Here's a concrete example. I have a hash map hashMap that uses an Integer as its key and a LinkedList as its value. The keys 5, and 10 are already in the hash map. The key 5 contains a LinkedList of Joey, Joe, Kerry. The key 10 contains the LinkedList of Jerry, Mary, Tim. I have two threads t1 and t2. t1 wants to add Moe to the LinkedList corresponding to key 5. t2 wants to add Harry to the LinkedList corresponding to key 10. Both will be concurrently added to the hash map, since the hash map's value is only locked.

My current implementation is a synchronized method. Would this allow two different threads to put two different keys simultaneously into the hash map?

No. Only a ConcurrentHashMap or a specifically designed concurrent map would support this safely, so it's impossible for you to put two keys simultaneously into the same map from two threads.

how would I make it possible that two different threads can put different keys simultaneously (concurrently) into the hash map?

You cannot, without using ConcurrentHashMap, another ConcurrentMap implementation, or implementing your own.