The Artima Developer Community
Sponsored Link

synchronization in ctrs



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 Artima Forums.


synchronization in ctrs

Posted by Julia Renouard on 23 Jul 1998, 2:30 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.

> bv

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

public MyClass
static Thread myThread;

public MyClass
synchronized (getClass())
if (myThread == null)


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us