Search code examples
javamultithreadingjava-memory-model

Java - object creation and visibility


Given the following code:

class MyObj{
   AtomicLong counter;

   public MyObj(){
       count = new AtomicLong();
   }
}

MyObj obj = new MyObj();
// start a few threads that referencey obj and access counter

I would like to know if there is a potential scenario here, that the created threads will see the state of MyObj as incomplete, due to compiler reodering/inlining? For instance, they might see counter = null, or counter partially created, as it is not a final field?


Solution

  • There are two situations:

    • if you start the threads after MyObj obj = new MyObj(), there is a happens-before relationship that guarantees that the threads will all see the correctly constructed object
    • if you start the threads before, there is no guarantee of anything (they could observe obj == null or obj != null && obj.counter == null or obj != null && obj.counter != null).