This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
synchronization in ctrs
Posted by Julia Renouard on 23 Jul 1998, 2:34 PM
> Synchronization works the same in a constructor as it does
> in a method, so it would certainly be possible to write
> RGBColor's constructor as you suggest.
> The one thing to note is that you don't need the synchronization
> in the constructor, because only one thread can ever be
> executing the code of the constructor at any one time. No
> other thread can get a reference to the object until after
> the construction of the object completes. Hence, you don't
> need to synchronize anything in the constructor. This means
> that any synchronization you add to the code executed by
> the constructor unecessarily gives you a performance hit. My
> philosophy is to avoid unecessary locking of objects, so
> I didn't call setColor() from the constructor.
> Note that you can write a constructor such that synchronization
> becomes important, though this way of writing a constructor
> goes against my "Constructors and initializers should just
> be about initialization, the whole initialization, and nothing
> but initialization" guideline. For example, from a constructor
> you could call a method in some other class or object and pass
> a reference to this (the object being constructed). That other
> method could give the reference to another thread which could
> try to invoke a method on the object. I can't imagine any good
> reason why someone would want to do this, but I'll bet it has
> probably happened somewhere.
I've recently been working with an example that has synchronization
the constructor - and for good reason. The class has a static
thread object that it only wants instantiated once. So the code
looks like this
static Thread myThread;
if (myThread == null)
myThread = new Thread(...);
The ctr actually puts a lock on the class so that we won't
try and create more than one thread if multiple instances of
the object are instantiated at once (i.e. from separate threads).
I hadn't seen any references to the use of getClass() this way,
but it will server me well in my static class methods that
need protection as well.