Java concurrency scenario — do I need synchronization or not?

后端 未结 10 1665
陌清茗
陌清茗 2021-02-01 07:19

Here\'s the deal. I have a hash map containing data I call \"program codes\", it lives in an object, like so:

Class Metadata
{
    private HashMap validProgramC         


        
10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 08:07

    The assignment will work as long as you're not concerned about reading stale values, and as long as you can guarantee that your hashmap is properly populated on initialization. You should at the least create the hashMap with Collections.unmodifiableMap on the Hashmap to guarantee that your readers won't be changing/deleting objects from the map, and to avoid multiple threads stepping on each others toes and invalidating iterators when other threads destroy.

    ( writer above is right about the volatile, should've seen that)

提交回复
热议问题