R. Clayton (rclayton@monmouth.edu)
(no date)
[ We talked yesterday in class about letting references to this escape duing
construction, which breaks both immutability and the one-reference rule.
Here's a real-life example of the problem, taken from the piccolo mailing
list. Piccolo is a zooming ui written in java.
The message also mentions that constructors cannot be declared syncrhonized,
which is something I don't think I ever mentioned. Don't forget to follow
the jcpnotes url. ]
--Date: Wed, 9 Jul 2003 09:55:23 +0200 (MET DST) Subject: RE: Piccolo: PFrame's initialize From: "Marco Nijdam" <marco@West.NL> To: piccolo-chat@cs.umd.edu Content-Type: text/plain;charset=iso-8859-1 Importance: Normal Sender: piccolo-chat-admin@cs.umd.edu
Dear Jesse,
As quoted from Grosjean, Jesse: > I also read here: > > http://rgarciasuarez.free.fr/java/jcpnotes.html > > that constructors CAN NOT be synchronized.
You're right, constructors are actually never synchronized. My memory failed me there.
So the problem is passing "this" (implicitly via the anonymous Runnable class) from the constructor to another thread. Conceptually the object is not fully constructed yet, so should not be used. The solution with a beforeInitialize method will probably work, but has the same conceptual problem: calling a method from a subclass while the subclass is not even constructed yet.
If you pass the "this" from the constructor to another thread, it seems to me it should be the last thing you do. It also means the class may not be subclassed (i.e. be final).
Requiring the caller to use an init method seems the cleaner solution to me. If you want a PFrame class mostly as a demo class, maybe you could make a PDemoFrame class that subclasses PFrame and is final, and calls the init method as last thing from the constructor.
Other solutions would be to make the constructor private and have a static method to create instances, or using a factory to create instances. But I guess those are no good solutions in this case, since it is very useful for Swing objects to have a default constructor (to use them as beans in a GUI build tool).
Kind regards, - -- - -- Marco Nijdam - -- _______________________________________________ Piccolo-chat mailing list Piccolo-chat@cs.umd.edu http://www.cs.umd.edu/mailman/listinfo/piccolo-chat
This archive was generated by hypermail 2.0b3 on Tue Aug 12 2003 - 09:30:05 EDT