Re: Constructor
Mike Schilling wrote:
[...]
Note that this kind of escape is a bad idea even if the constructor will
(eventually) succeeed, since it makes a partially constructed object visible
to other threads. NetBeans used to use a pattern like this for its
DataObjects (roughly, objects that represent a file known to the IDE)
abstract class DataObject
{
protected DataObject()
{
register(this); // add this to the global list of DataObjects
}
}
The result, that other threads in the IDE would now see partially
constructed objects, caused intermittent and intractable problems. I don't
know (and don't at this point really much care) whether this has been fixed.
Is there a good solution to the problem, that is, a good way
to maintain a "registry" or other collection of all constructed
instances of a class? The approaches I can think of all seem to
have drawbacks:
- Use the pattern shown above, with the drawback that the
registration occurs before the subclass constructor runs.
- Make the class final so there's no subclass constructor to
worry about, with the drawback that the class can't be
extended. (There may also be a quibble that construction
isn't really "finished" at the time of registration, even
if registration is the last action the constructor takes.)
- Make all the constructors private and use factory methods,
with the drawback that the class can't be extended. (This
approach avoids the quibble mentioned above, assuming the
registration occurs in the factory rather than in the
constructor.)
- Write Javadoc imploring all users to call .register() on each
instantiation of the class or a subclass. (Lotsa luck...)
- Just give up on the idea of a global registry, and get someone
to declare the idea an anti-pattern. When asked for greater
functionality, shrug and say "That would require a registry,
and Higher Authority forbids them."
Is there a better approach?
--
Eric.Sosman@sun.com