Does mutation of an non-thread-safe collection in a constructor need to be synchronized?

后端 未结 4 1462
庸人自扰
庸人自扰 2021-02-19 02:20

If I decide to use a non-thread-safe collection and synchronize its access, do I need to synchronize any mutation in the constructor? For example in the following code, I under

4条回答
  •  终归单人心
    2021-02-19 03:00

    Because the object is not inherently immutable, you must safely publish the object. As long as you do this, there is no need to do the mutations in the constructor in a synchronized block though.

    Objects can be "safely published" in a number of ways. An example is passing them to another thread via a properly synchronized queue. For more details see Java Concurrency in Practice section 3.5.3 "Safe publication idioms" and 3.5.4 "Effectively Immutable Objects"

提交回复
热议问题