[concurrency-interest] do constructors ever involve threading under the covers?

Aleksey Shipilev aleksey.shipilev at oracle.com
Wed Oct 3 10:23:02 EDT 2012


On 10/03/2012 06:04 PM, Andy Nuss wrote:
> The reason I ask about the constructor is this: java memory model
> provides a guarantee that all memory set/changed in the constructor is
> immediately visible to any other thread (that receives a reference to
> new object) after the constructor returns.  Is this true?

Ughm, there is a requirement for the final field values of newly
constructed objects set in constructor are visible after constructor
finishes, and only in the case if you haven't leaked the reference to
"this" in the constructor.

There is no memory semantics for constructor invocation otherwise. I.e.:

class A {
   private int myField;

   public int get() {
      // DOES NOT force $myField visibility
      return new B(myField).value;
   }
}

class B {
   final int value;
   public B(int v) { value = v; }
}

> Is the contructor always executed in the same thread as its caller?

Yes, it acts like ordinary method in this regard, no specific implicit
treatment.

-Aleksey.



More information about the Concurrency-interest mailing list