HashMap and concurrency- different keys

前端 未结 4 1777
一生所求
一生所求 2021-01-20 04:58

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 differ

4条回答
  •  孤独总比滥情好
    2021-01-20 05:18

    The easiest answer is to use a ConcurrentHashMap, which does exactly what you're looking for.

    If you can't do that (I see you edited your post after I answered), then you'll have to duplicate the same thing that ConcurrentHashMap does. No, simply synchronizing the method of a HashMap will not allow two threads to add a key-value pair at the same time, they have to wait and go one at a time.

提交回复
热议问题