File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes private constructors - singleton pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "private constructors - singleton pattern" Watch "private constructors - singleton pattern" New topic

private constructors - singleton pattern

Paul Keohan
Ranch Hand

Joined: Mar 15, 2000
Posts: 411
If you want to create a class as a singleton which extends from another singleton, how would you go about it? You normally can't compile a class that extends from a class which has a private constructor. If this sounds like an idiotic thing to be doing in the first place, I'd welcome all opinons.
Vin Kris
Ranch Hand

Joined: Jun 17, 2002
Posts: 154
Idiotic? No. Tricky? Yes.
Create a separate package for you singletons. Give your constructor of the derived class private access. Do NOT specify any access modifier to your base singleton class. Give protected access to the static variable of the base class that represents your singleton instance.

At the end, your final singleton would ofcourse be an object of your derived class. Therefore, it raises some more questions that you'd have to workaround a little bit.
Two problems with this approach - one thread may invoke Base.instance() whereas another may invoke Derived.instance().
1) More than 1 Base objects are created.
2) you'd have concurreny issues. (ofcourse, concurreny issues exist even for the singleton creation logic - search in google).
You can solve these problems by explicitly invoking Derived.instance() whenever your application is re-started. That should solve a lot of other problems.
I haven't yet worked out all the cases - so if you find any glaring mistake, be liberal.
I agree. Here's the link:
subject: private constructors - singleton pattern
It's not a secret anymore!