The Artima Developer Community
Sponsored Link

Synchronization in constructors

Advertisement

Advertisement

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.

Message:

Synchronization in constructors

Posted by Bill Venners on 21 Jul 1998, 9:08 AM

> In your example, you have a (minor) duplication of code in
> your constructor, you could have used:

> RGBColor(int r, int g, int b) {
> setColor(r,g,b);
> }

> Did you do this deliberately since setColor() is
> synchronized? What is the effect of sychronized(this)
> when "this" is an object under construction?

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



Replies:

Sponsored Links



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