Java Memory Model: Is it safe to create a cyclical reference graph of final instance fields, all assigned within the same thread?

前端 未结 2 1737
暗喜
暗喜 2021-02-19 11:18

Can somebody who understand the Java Memory Model better than me confirm my understanding that the following code is correctly synchronized?

class Foo {
    priv         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 12:10

    Immutable Objects (with only final fields) are only "threadsafe" after they are properly constructed, meaning their constructor has completed. (The VM probably accomplishes this by a memory barrier after the constructor of such objects)

    Lets see how to make your example surely unsafe:

    • If the Bar-Constructor would store a this-reference where another thread could see it, this would be unsafe because Bar isnt constructed yet.
    • If the Bar-Constructor would store a foo-reference where another thread could see it, this would be unsafe because foo isnt constructed yet.
    • If the Bar-Constructor would read some foo-fields, then (depending on the order of initialization inside the Foo-constructor) these fields would always be uninitialized. Thats not a threadsafety-problem, just an effect of the order of initialization. (Calling a virtual method inside a constructor has the same issues)

    References to immutable Objects (only final fields) which are created by a new-expression are always safe to access (no uninitialized fields visible). But the Objects referenced in these final fields may show uninitialized values if these references were obtained by a constructor giving away its this-reference.

    As Assylias already wrote: Because in your example the constructors stored no references to where another thread could see them, your example is "threadsafe". The created Foo-Object can safely be given other threads.

提交回复
热议问题