I want to create only one object of an class and reuse the same object over and over again. Is there any efficient way to do this.
How can I do this?
I want to create only one object of an class and reuse the same object over and over again. Is there any efficient way to do this.
How can I do this?
public final class MySingleton {
private static volatile MySingleton instance;
private MySingleton() {
// TODO: Initialize
// ...
}
/**
* Get the only instance of this class.
*
* @return the single instance.
*/
public static MySingleton getInstance() {
if (instance == null) {
synchronized (MySingleton.class) {
if (instance == null) {
instance = new MySingleton();
}
}
}
return instance;
}
}
This is generally implemented with the Singleton pattern but the situations where it is actually required are quite rare and this is not an innocuous decision.
You should consider alternative solutions before making a decision.
This other post about why static variables can be evil is also an interesting read (a singleton is a static variable).
The simplest way to create a class with one one instance is to use an enum
public enum Singleton {
INSTANCE
}
You can compare this with Steve Taylor's answer to see how much simple it is than alternatives.
BTW: I would only suggest you use stateless singletons. If you want stateful singletons you are better off using dependency injection.
That would be the Singleton pattern - basically you prevent construction with a private constructor and "get" the instance with a static synchronized getter that will create the single instance, if it doesn't exist already.
Cheers,
You are looking for the Singleton pattern. Read the wikipedia article and you will find examples of how it can be implemented in Java.
Perhaps you'd also care to learn more about Design Patterns, then I'd suggest you read the book "Head First Design Patterns" or the original Design Patterns book by Erich Gamma et al (the former provides Java examples, the latter doesn't)