aspose file tools*
The moose likes Java in General and the fly likes Generic Singleton Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generic Singleton Class" Watch "Generic Singleton Class" New topic
Author

Generic Singleton Class

Kumar Jaya
Ranch Hand

Joined: Jan 12, 2009
Posts: 45
Hello,

Can I create a generic (Parameterized) Singleton class?

public class SingleTon<T> {

private static SingleTon instance; //I am getting warning message here...

}

I tried but in vain, I am not able to declare my private static instance variable??

Can any one help me??

Regards
Jaya
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39834
    
  28
Maybe you can use

private static final Singleton<T> instance;

instead. Using final will reduce the risk of your instantiating it twice by mistake.
Vaman Kulkarni
Greenhorn

Joined: Nov 06, 2009
Posts: 7
I guess you should supply the type while creating instance.


Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
What's the message you get?
Kumar Jaya
Ranch Hand

Joined: Jan 12, 2009
Posts: 45
What's the message you get?


Hi Embla,

A Samle SingleTon Class

class singleton {
private static singleton instance;

static {
instance = new singleton();
}

public static singleton getInstance() {
return instance;
}
}

Now I want to parameterize this singleton so.., I will have to do something like this..


class singleton<T> {

private static singleton instance;

// I get warning here in above line saying ->singleton is a rawtype. Reference to generic type should be parameterized.... I cannot parameterize a static reference also??? right???

static {
instance = new singleton();
}

public static singleton getInstance() {
return instance;
}
}

suppose I want to instantiate this singleton.., I will do something like this..

singleton<Integer> singleInt = singleton<Integer>.getInstance(); // This wont work since I cannot parameterize the line I get the warning..

I think you get it???


Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18907
    
    8

Well, first of all your declaration inside the class will have to be

That's because your singleton object is supposed to be of type T, right? And your getInstance method would be

So far so good. But now you have the problem of creating an instance of an unknown type. No, you can't write "instance = new T()" if you were going to try that. The standard way to deal with this in Generics is to pass in the actual class as a parameter. So your getInstance method would change to be

and your code to get the singleton object in the caller would look like this

Next you have the problem of creating an object of a type T when you're given the Class object for that type. Here you use reflection: Class<T> has a method newInstance() which creates an object of type T, using its no-arguments constructor. Note that there's an assumption built in that T actually has such a constructor. If it doesn't, you'll have to use a more complicated method of creating a T object and pass it suitable parameters -- I don't want to go into that, you can figure it out if the question arises.

Personally I wouldn't do all of this. I don't use singletons nearly enough to need a generic way of creating them, so I wouldn't bother. But if you want to do it, because you have a singleton-happy designer passing you specs or just for the challenge of doing it, hopefully that gets you started.

(Edit: I didn't compile any of that so it might not be entirely correct.)
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Kumar Jaya wrote:I think you get it???


It seems like a problem that cannot be solved without an unsafe downcast somewhere.

This is the best solution I can come up with,


As you can see the singleton reference (returned by getInstance) must be downcasted so that's not typesafe. On the other hand this downcast must match the type of the reference variable (singletonString and singletonInteger) so you actually get a typecheck at compiletime. This means the downcast is typesafe in practice so the last step would be to suppress the compiler warning with @SuppressWarnings("unchecked").
Lorand Komaromi
Ranch Hand

Joined: Oct 08, 2009
Posts: 276
Embla Tingeling wrote:
Kumar Jaya wrote:
his means the downcast is typesafe in practice


No it is not, you can assign the instance to a singleton<String> reference and set variable then assign it to a singleton<Integer> and try to use it as an Int. At runtime the JVM can't tell whether the singleton instance contains a String or Int, because of this, it can't check the cast and throw a ClassCastException before you try to do something really silly...


OCJP 6 (93%)
Lorand Komaromi
Ranch Hand

Joined: Oct 08, 2009
Posts: 276
Embla Tingeling wrote:
Kumar Jaya wrote:
his means the downcast is typesafe in practice


No it is not, you can assign the instance to a singleton<String> reference and set variable then assign it to a singleton<Integer> and try to use it as an Int. At runtime the JVM can't tell whether the singleton instance contains a String or Int, because of this, it can't check the cast and throw a ClassCastException before you try to do something really silly...
Lorand Komaromi
Ranch Hand

Joined: Oct 08, 2009
Posts: 276
Embla Tingeling wrote:
his means the downcast is typesafe in practice


No it is not, you can assign the instance to a singleton<String> reference and set variable then assign it to a singleton<Integer> and try to use it as an Int. At runtime the JVM can't tell whether the singleton instance contains a String or Int, because of this, it can't check the cast and throw a ClassCastException before you try to do something really silly...
Lorand Komaromi
Ranch Hand

Joined: Oct 08, 2009
Posts: 276
Hmm, I tried to edit my reply and it got posted 3 times.
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Lorand Komaromi wrote:
Embla Tingeling wrote:
his means the downcast is typesafe in practice


No it is not,


Could you supply an example of what you mean (preferrably based on the code I posted).
Vivek Singh
Ranch Hand

Joined: Oct 27, 2009
Posts: 92
Campbell Ritchie wrote:Maybe you can use

private static final Singleton<T> instance;

instead. Using final will reduce the risk of your instantiating it twice by mistake.


This is the best and smartest way to introduce Singleton.
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Vivek Singh wrote:
Campbell Ritchie wrote:Maybe you can use

private static final Singleton<T> instance;

instead. Using final will reduce the risk of your instantiating it twice by mistake.


This is the best and smartest way to introduce Singleton.


I don't agree, the enum Singleton is both better and smarter. The problem is that an enum cannot be generic so it doesn't solve the OP's problem.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Campbell Ritchie wrote:private static final Singleton<T> instance;


or define a private Constructor .
Kumar Jaya
Ranch Hand

Joined: Jan 12, 2009
Posts: 45
Well, first of all your declaration inside the class will have to be
view plaincopy to clipboardprint?

1. private static T instance;

private static T instance;
That's because your singleton object is supposed to be of type T, right?


This is not permited as you cant have a static Type..

I am trying from all the posts from Paul, Embla to find out a way..

Anyway thanks to all..

Regards
Jaya
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Kumar Jaya wrote:I am trying from all the posts from Paul, Embla to find out a way..


Good luck.

I still claim that the downcast in my solution is typesafe but I'll change my mind if Lorand Komaromi manages to come up with a counterexample showing it is not.
Lorand Komaromi
Ranch Hand

Joined: Oct 08, 2009
Posts: 276
Embla Tingeling wrote:
I still claim that the downcast in my solution is typesafe but I'll change my mind if Lorand Komaromi manages to come up with a counterexample showing it is not.


I was wrong about the ClassCastException, it WILL be thrown because the compiler had inserted casts at compile time. Still, you loose compile-time type safety:

Kumar Jaya
Ranch Hand

Joined: Jan 12, 2009
Posts: 45
Thanks Lorand Komaromi and Embla Tingeling,

The discussion was really good, but I still dont have a complete understanding, and have some doubts lurking in my mind.

1) I far as I understood, generics was introduced to remove unnecessary casts, so even if I use generics I cannot go without the downcast in the example. So I cant justify such a design.

2) Singleton pattern has a prime purpose of having only one instance of its kind. So if I use a non generic instance such as

Singelton sTon = Singleton.getInstance();...

I will get an instance of a singleton if this call is for the first time, and in any other part of my coding classes if I use the same statement like

Singleton sTonn = SingleTon.getInstance(); should return the same instance. (like sTon == sTonn)..

Now if I used generics

Singleton<Integer> sInt = Singleton<Integer>.getInstance();

and

Singleton<String> sString = Singleton<String>.getInstance();

I will be having ideally two instances sInt and sString where (sInt != sString), so if I do the same
Singleton<Integer> sIntt = Singleton<Integer>.getInstance(); some where down the code will I get (sInt == sIntt or sInt != sIntt)??

Also one final thing from a more practical point

Suppose I have a more generic class like

class myclass <T extends Something<ID>, ID> {
....
}

can I create a singleton implementation for myclass??

Once again I really thank for your time.

Regards
Jaya

Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Kumar Jaya wrote:and have some doubts lurking in my mind.


So do I actually.

I've search a little on the internet and there doesn't seem to be a good generic Singleton solution available. It's seems to be beyond Java generics.

My suggested solution doesn't seem to work properly so I suggest you forget about it.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Seems to me like you don't actually want a Singleton, you are probably better off with a mapping of the Type to the Instance, and a method to make sure that there is only one instance in play. To me that suggests using a Factory class with access to a particular Type's Instance protected by synchronization. For example, if we replace your Singleton class with a Generic interface like below:


We could have an Factory (which is a Singleton, but not the 'Generic Singleton' you were talking about) like this:


I haven't tested so much, but I think this would provide Thread-Safe 'singleton' instances per-type since all accesses to the instance are synchronized on the Class object. You could use it like this:


Steve
Kumar Jaya
Ranch Hand

Joined: Jan 12, 2009
Posts: 45
Thanks Steve,

I will give this a try.

Regards
Jaya
 
wood burning stoves
 
subject: Generic Singleton Class