Java concurrency scenario — do I need synchronization or not?

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

    No, by the Java Memory Model (JMM), this is not thread-safe.

    There is no happens-before relation between writing and reading the HashMap implementation objects. So, although the writer thread appears to write out the object first and then the reference, a reader thread may not see the same order.

    As also mentioned there is no guarantee that the reaer thread will ever see the new value. In practice with current compilers on existing hardware the value should get updated, unless the loop body is sufficienly small that it can be sufficiently inlined.

    So, making the reference volatile is adequate under the new JMM. It is unlikely to make a substantial difference to system performance.

    The moral of this story: Threading is difficult. Don't try to be clever, because sometimes (may be not on your test system) you wont be clever enough.

提交回复
热议问题