dcsimg
Why does Java prohibit the use of "synchronized" on a constructor?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Richard_Robinson
Posted On:   Friday, April 13, 2001 12:07 PM

I'm unclear about constructors in general, and how they relate to multithreading in particular. Common advice is to make member variables (instance and static) private and synchronize public methods in a class. As well, and in particular, to synchronize getter/setter methods. Java prohibits the using of "synchronized" on a constructor. So I'm guessing that when an object is first created, ie. constructed, that there is ONE and ONLY ONE thread that does the construction? If this is right, then what happens after the first object is created and another object in the same calling object tries to construct the object again. If the to-be-constructed object has several instance variables and the constructor sets th   More>>

I'm unclear about constructors in general, and how they relate to multithreading in particular. Common advice is to make member variables (instance and static) private and synchronize public methods in a class. As well, and in particular, to synchronize getter/setter methods.


Java prohibits the using of "synchronized" on a constructor. So I'm guessing that when an object is first created, ie. constructed, that there is ONE and ONLY ONE thread that does the construction?


If this is right, then what happens after the first object is created and another object in the same calling object tries to construct the object again. If the to-be-constructed object has several instance variables and the constructor sets them... Even if the setter methods are synchronized, isn't there a concurrency issue at work between when the constructor sets the one value and the subsequent call to set the next one?

   <<Less

Why does Java prohibit the use of &quot;synchronized&quot; on a constructor?

Posted By:   Alex_Chaffee  
Posted On:   Monday, April 30, 2001 04:37 PM

You can't construct an object more than once. You can construct a different instance of
the same class. But the scenario you describe is impossible. So stop worrying :-)


To be specific: the constructor is called *during* the call to new. Before that call returns, there is *no* pointer (handle) to that object. So no other thread can ever call a method on that instance, until it returns with a valid pointer.


Note that you may still need to synchronize access to the static data members of a class when called inside a constructor.

About | Sitemap | Contact