Re: Synchronization of the constructor
On 8/13/2011 6:36 AM, Eric Sosman wrote:
On 8/13/2011 5:58 AM, MaciekL wrote:
Hi,
I have a doubt because Java disables synchronization of the constructor
by default.
The constructor can be synchronized,
It really can't. Recall that the compiler will insert a call to a super
constructor if the first statement doesn't have a such a call or a call
to another class constructor. Consider this:
public class SomeClass {
public SomeClass() {
synchronized( SomeClass.class ) {
...
}
}
....
What you get is this:
public class SomeClass {
public SomeClass() {
super();
synchronized( SomeClass.class ) {
...
}
}
....
And thus you see that some writes in the construction occur outside of
the synchronized block, a classic case of incorrectly written
synchronization.
The closest Java gets to a synchronized constructor is immutable objects
made with final fields.
public class Immutable {
private final SomeObject o;
public Immutable() {
o = new SomeObject();
}
....
This is thread safe, and immutable, because the fields written are
declared "final." Java takes special processing at the end of the
constructor to synchronize all final fields, and any writes made to
objects accessible via those final fields, with all other threads in the
system. So now this Immutable class can be used safely by any thread in
the system.