File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "private constructors - singleton pattern" Watch "private constructors - singleton pattern" New topic
Author

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.
Thanks.
Paul
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: http://aspose.com/file-tools
 
subject: private constructors - singleton pattern
 
Similar Threads
Singleton Question
Why constuctor can't be marked as final?
Singleton Class
Understanding singleton pattern
Clarifications/Suggestions in Java