Is setting a HashMap thread safe?

后端 未结 4 2082
北荒
北荒 2021-02-20 10:39

I have a HashMap in my program which is accessed by multiple threads, and is occasionally set by a single thread.

For example:

Map

        
4条回答
  •  野的像风
    2021-02-20 10:51

    If you mean you are creating an entirely new Map and are assigning it to myMap which is what the other threads are accessing, then yes. Reference assignment is atomic. It's threadsafe because you are not modifying the contents of a Map while other threads are reading from it - you just have multiple threads reading from a Map.

    You just need to declare it volatile so other threads don't cache it.

提交回复
热议问题