Java concurrency scenario — do I need synchronization or not?

后端 未结 10 1565
陌清茗
陌清茗 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:10

    No, the code example is not safe, because there is no safe publication of any new HashMap instances. Without any synchronization, there is a possibility that a reader thread will see a partially initialized HashMap.

    Check out @erickson's explanation under "Reordering" in his answer. Also I can't recommend Brian Goetz's book Java Concurrency in Practice enough!

    Whether or not it is okay with you that reader threads might see old (stale) HashMap references, or might even never see a new reference, is beside the point. The worst thing that can happen is that a reader thread might obtain reference to and attempt to access a HashMap instance that is not yet initialized and not ready to be accessed.

提交回复
热议问题