> What object could it synchronize on? There is no
> object until the constructor returns, so no
> possibility that two threads could both use it.
Actually, this isn't true. The "new" is what creates the object, and of course the object exists when the constructor starts -- it's the object that the "this" reference points to.
I don't see any reason that the constructor couldn't arrange for another thread to access the partially constructed object, but I do agree that doing that would be a collossal design error! ;-)
No, that's still not true. The object exists before the constructor is called.
The code
Object o = new Object();
compiles into the bytecodes
0 new #2 <Class java.lang.Object>
3 dup
4 invokespecial #1 <Method java.lang.Object()>
7 astore_1
It is the "new" instruction that creates the object and puts a reference to the object on the stack. The dup instruction duplicates this reference so that it's passed to the constructor by the invokespecial instruction. When the constructor is invoked, there is an object that can be locked on.
However, as I've said, it would be horrible to have another thread access the object before it's fully constructed, so a synchronized constructor makes no sense because that would be the only use for it.
> Object o = new Object();
>
> compiles into the bytecodes
>
> 0 new #2 <Class java.lang.Object>
> 3 dup
> 4 invokespecial #1 <Method java.lang.Object()>
> 7 astore_1
> When the constructor is invoked, there is
> an object that can be locked on.
>
> However, as I've said, it would be horrible to have
> another thread access the object before it's fully
> constructed, so a synchronized constructor makes no
> sense because that would be the only use for it.
Hi,
yes, and such an access before the object isn't fully constructed has to be programmed with pseudo-assembler and be inserted in the byte-code of the java-class - that is not programmable in java directly, because that reference to that unfinished object is available at address 3 above for the first time, right in the middle of the statement "Object o = new Object();" - you can't insert java-code there and therefore there is no need to make a constructor synchronized.
greetings Marsian