Note that some code somewhere has to call something like: new TheObject() for the constructor to be run. Since a constructor is only run while the object is being created, thread safety of the constructor itself is not an issue. This is because two threads can't create the same object. If they are creating objects, they will create different ones. Thus it does not make sense to have a synchronized keyword for a constructor. Now what the constructor is doing is another matter. If it is accessing some common resource (another object or static methods/fields) then there could be a problem. But this is no different than any method's access of those resources. Those resources should be protected in either case.
Originally posted by Dave Landers: Note that some code somewhere has to call something like: new TheObject() for the constructor to be run.
This is, in the strictest technical sense, not the case. Consider: 1) constructors call other constructors in the same class if they are chained together (as in this()); 2) child constructors call parent constructors prior to completing.
Joined: Jul 24, 2002
OK, to clarify what I meant. In order for an object to be constructed (and thus have some combination of constructors invoked) somebody has to make a call to new. While that is going on, other threads can not get a reference to that object until it is constructed (exception -see below). And in any case when another gets the instance, it can not invoke the constructor. A second threads can not invoke any constructor on the same object instance. Therefore the constructors themselves are "thread-safe", and the only concern is the thread safety of objects that are used by those constructors. Exception: What I said above about "other threads can not get a reference till it is constructed" is not strictly true. It is true enough for the explaination above, but it still has a hole. The reason is all wrapped up in the Java Memory Model. Its the same reason that Double Checked Locking doesn't work in Java. Don't need to go into that into too much detail here.
Joined: Aug 28, 2002
Thanks for your inputs guys. They got certain constructor issues cleared.
Slightly relevant: Some things not to do within a constructor: a)let the reference "this" to scape. For instance recording it in a field, or calling a method passing it as argument. b)calling methods that could be overriden They both could try to access the instance fields before they are fully initialized.