Java Hashmap - Multiple thread put

前端 未结 2 2015
北海茫月
北海茫月 2021-01-12 21:39

We\'ve recently had a discussion at my work about whether we need to use ConcurrentHashMap or if we can simply use regular HashMap, in our multithreaded environment. The arg

相关标签:
2条回答
  • 2021-01-12 22:03

    What you're faced with seems to be a TOCTTOU class problem. (Yes, this kind of bug happens so often, it's got its own name. :))

    When you insert an entry into a map, at least the following two things need to happen:

    1. Check whether the key already exists.
    2. If the check returned true, update the existing entry, if it didn't, add a new one.

    If these two don't happen atomically (as they would in a correctly synchronized map implementation), then several threads can come to the conclusion that the key doesn't exist yet in step 1, but by the time they reach step 2, that isn't true any more. So multiple threads will happily insert an entry with the same key.

    Please note that this isn't the only problem that can happen, and depending on the implementation and your luck with visibility, you can get all kinds of different and unexpected failures.

    0 讨论(0)
  • 2021-01-12 22:04

    In multi thread environment, you should always use CuncurrentHashMap, if you are going to perform any operation except get.

    Most of the time you won't get an exception, but definitely get the corrupt data because of the thread local copy value.

    Every thread has its own copy of the Map data when performing the put operation and when they check for key existence, multiple threads found it false and they enter the data.

    0 讨论(0)
提交回复
热议问题