Why does Java prohibit the use of "synchronized" on a constructor?

Alex Chaffee

[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?]

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. Once the constructor returns with a valid pointer, then other threads may conceivably call methods on it.

In fact, at the moment the constructor is called, the object has not been created yet -- which means there is no lock to synchronize on. That's why it's prohibited.

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

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.