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

Andy Nuss andrew_nuss at yahoo.com
Wed Oct 3 10:22:55 EDT 2012

(It was a reply accident that I did not reply to list.)

So if I follow you correctly, for a constructor that has an array or ArrayList member, creates that array/ArrayList, and fills it with a bunch of seeded values, which are effectively final: another thread will not see the values in the array/ArrayList unless the constructed object is "published" to the other thread, such as with a volatile variable or concurrent map.

In that case, can someone explain to me how java String, which holds an array of characters, is threadsafe without the need for publishing the string to the other thread?  I.e. even if the array reference is final, the "final" attribute does not apply to the elements of the array.  Same with a final ArrayList reference.

 From: Aleksey Shipilev <aleksey.shipilev at oracle.com>
To: Andy Nuss <andrew_nuss at yahoo.com> 
Sent: Wednesday, October 3, 2012 7:11 AM
Subject: Re: [concurrency-interest] do constructors ever involve threading under the covers?
Any specific reason you are not replying to the list? :)

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 A(myField).value;

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

Neither it would change if you make B.v final.

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

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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20121003/ed4280d0/attachment.html>

More information about the Concurrency-interest mailing list