How thread safe are immutable objects?

后端 未结 4 1713
一整个雨季
一整个雨季 2021-01-18 04:22

Everybody says that immutable objects are thread safe, but why is this?

Take the following scenario running on a multi core CPU:

  • Core
4条回答
  •  逝去的感伤
    2021-01-18 05:08

    I'm not sure that a memory gate would change this scenario, as that would surely only affect subsequent reads... and then the question becomes reads from where? If it is from a field (which must at a minimum be static or an instance fields for some instance still on the stack or otherwise reachable), or local variable - then by definition it isn't available for collection.

    Re the scenario where that reference is only now in the registers... that is far trickier. Intuitively I want to say "no that isn't a problem", but it would take a detailed look at the memory model to prove it. But handling references is such a common scenario that simply: this has to work.

提交回复
热议问题