JavaMemoryModel: Should we allow synchronized constructors?

From: Bill Pugh (pugh@cs.umd.edu)
Date: Fri Jan 04 2002 - 23:17:27 EST


[This came up in a discussion with Hans Boehm -- Bill]

There are a number of circumstances in which it would be useful to
synchronize constructors; if you need make an object visible to
other threads during construction, and want to use synchronization to
prevent methods from being invoked on the object until after
construction is complete.

In fact, constructors are the only method that really cries out for
synchronization in the method declaration, since it allows you to do
something you can't do with synchronized(this) { ... }. Using
synchronized (this), you can't get the lock until after the call to
the constructor for the superclass returns.

The JLS spec says synchronized constructors aren't allowed,
explaining (incorrectly) that this is since synchronized constructors
wouldn't be useful.

However, as far as I can tell, the JVMS allows <init> methods to have
the ACC_SYNCHRONIZED flag set, even though you can't set this bit in
the output from javac.

I also tried constructing some class files with synchronized
constructors, and ran it with -Xfuture -Xverify:all under 1.4beta3,
and no errors were generated. However, as far as I can tell, Hotspot
completely ignores ACC_SYNCHRONIZED in <init> methods.

So, are the JVM implementors happy/content with the idea of dealing
an additional requirement of handling with classfiles that have
synchronized <init> methods? Does this cause any issues in the
implementation?

And if we decide to handle it in classfiles, do we also want to
change the Java source syntax to allow it?

        Bill
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:37 EDT