[concurrency-interest] synchronized constructors

Ruslan Cheremin cheremin at gmail.com
Fri Dec 16 07:24:12 EST 2011

> Okay, then JVM spec 8.8 says that no “lock” operation can take place between a relocated “store” and its “assign”, so we are safe here, i.e. synchronized {} within constructor makes even unsafe publication impossible before the lock is entered.

It seems like good point, althought I still does not sure about this
reasoning. I need some time for more formal proof.

>The remaining problem is that without acquiring the lock from the other thread, that thread may see partially initialized state. So to make sure that everything is okay, is it enough to have one final field which forces publication to happen after the constructor finishes?

As far, as I understand, topic starter does not want to elide locks
from other threads. Contrary, he wants to protect _all_ methods of his
object with locks -- making them completely thread-safe, even in case
of data-race-based publication. And he asks, is protecting constructor
does this job, and if it is - why synchronized constructor is
prohibited in JLS?

By the way -- one final field does not enough. Final field is not a
magic for everybody -- it's magic is for itself (and its dereference
chain) only. Although it seems like most of actual implementation use
global StoreStore barrier (if any) as freeze, making _all_ previous
write published, such global barrier does not required by formal JMM
final field semantic. And JMM does not prevent JIT to move some
non-final-fields write _after_ freeze.

>> But JMM does not specify memory effects
>> of locking as “fresh reads after lock” or “writes flushed before
>> unlock” -- memory effects specified in terms of HB-edges lock/unlock
>> creates. And if such edges are redundant -- they are still exists even
>> without specific lock, since, for example, the same edges are created
>> by program order -- the lock can be thrown out, and this does not
>> change memory semantics (full set of HB edges in execution will not be
>> changed). This is one of the greatest benefits of new JMM, which
>> allows kind of optimization I've noted (lock ellision/biased locking).
> Yes, certainly. Unless it becomes impossible to create a mutable object which has the same memory visibility guarantees wrt. construction as compared to one which has only final fields.

It seems like it is. Seems like the only way to work with data races
and got some predictable results is to use final fields.

> Regards,
> Roland
> --
> I'm a physicist: I have a basic working knowledge of the universe and everything it contains!
>    - Sheldon Cooper (The Big Bang Theory)

More information about the Concurrency-interest mailing list