Java Hashmap - Multiple thread put

前端 未结 2 2043
北海茫月
北海茫月 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.

提交回复
热议问题