Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

No Listener in constructor

Thread view: 
Philipp - 23 Oct 2007 16:17 GMT
Hello
I heard that one should not register an object as a listener for some
events during its construction because an event could be triggered
before the object is completely constructed.

What do you think about this?

Thanks Philipp
Lew - 23 Oct 2007 16:36 GMT
> I heard that one should not register an object as a listener for some
> events during its construction because an event could be triggered
> before the object is completely constructed.
>
> What do you think about this?

Good advice.

Constructors are for construction, only.  Logic belongs in methods.  The
object isn't constructed until the constructor finishes, so generally one
should not do anything non-constructive (such as calling an overridable method
or registering an event listener) in a constructor.

Signature

Lew

Daniel Pitts - 23 Oct 2007 17:51 GMT
> Hello
> I heard that one should not register an object as a listener for some
[quoted text clipped - 4 lines]
>
> Thanks Philipp
For one thing, it is a thread safety issue.  Along with the general
practice that you should not allow the "this" pointer to escape during
construction.  The "this" pointer is only fully valid once the
constructor has completed normally.  If you need to register listeners
as part of the instantiation process, consider using a static factory
method which instantiates a private constructor, and then attaches that
instance to the appropriate places.

If you want an indepth explanation of why it is dangerous, along with a
lot of other good-to-have understanding of multi-threaded programming, I
suggest getting the book /Java Concurrency In Practice/. You can read my
short review of it at
<http://virtualinfinity.net/wordpress/technical-book-recommendations/>
.

Good luck,
Daniel.
Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.