Java Singleton Design Pattern implementation [duplicate] - java

This question already has answers here:
How to write a Singleton in proper manner?
(13 answers)
Closed 8 years ago.
Can the implementation for a Singleton class can be as simple as below :
public class MyClass {
private final static MyClass myClass = new MyClass();
private MyClass() {}
public static MyClass getInstance() {
return myClass;
}
}
Over :
public class MyClass {
private final static MyClass myClass;
private MyClass() {}
public static MyClass getInstance() {
if(null == myClass) {
myClass = new MyClass();
}
return myClass;
}
}
Which is the better of the above implementations & why?
One thing that I observed is for the first implementation above the object constructor gets called before the static block if any.
Also if there is a thread-safe version of the 2nd implementation (may be a double null check and synchronized block), which should be preferred ?

Yes. And you can use that first version, but I would suggest you use an enum. Wikipedia's entry on Singleton says
In the second edition of his book Effective Java, Joshua Bloch claims that a single-element enum type is the best way to implement a singleton for any Java that supports enums.
Something like
public enum Singleton {
INSTANCE;
}

I would like to put some light on singleton design pattern.
Your First Code Snippet
public class MyClass {
private final static MyClass myClass = new MyClass();
public static MyClass getInstance() {
return myClass;
}
}
The above approach works fine but has drawback as instance is getting created much before actually it is required so at run-time think of the situation that if the instance is not big you can keep it if it is unused but if it big then what is the purpose of creating the instance.This approach is called Eager initialization
The code shown below indicates the second approach called Lazy initialization
public class MyClass {
private final static MyClass myClass;
public static MyClass getInstance() {
if(null == myClass) {
myClass = new MyClass();
}
return myClass;
}
}
But here again there is one drawback in your code,let's understand the defect in the above code
Let's consider we have tow threads namely T1 and T2 and both threads are intended to create the instance and executes the check null == myClass,now both threads have identified instance variable to null thus assume they must create an instance. They sequentially goes to synchronized block and create the instances. At the end, we have two instances in our application.
This can be resolved by simply double check locking. Below code will show you the better way of implementation. Just note- I have used private constructor in code.
public class MyClass {
private final static MyClass myClass = null;
//private constructor
private MyClass(){
}
public static MyClass getInstance() {
if(myClass == null) {
synchronized (MyClass.class){
// Double check
if(myClass == null){
myClass = new MyClass();
}
}
}
return myClass;
}
}

The principle rules which yoy need to take care to define the singleton class is :
Private constructors - which restricts the object creation from other classes
Private static field variable which holds the only instance of the same class
A public static method which is used to return this instance when requested
It depends on how you want it, whether you want early initialization or lazy initialization. The first one is an example of early initialization, while the second one is an example of lazy initialization. There are multiple ways to define a perfect Singleton Class

Related

Use factory to build singleton object

I'm trying to create some singleton object with a factory:
public class MyObjectFactory {
private MyObject myObject;
public MyObject getInstance(boolean newInstance) {
if (newInstance) {
// return new object
} else {
// return the old object
}
}
}
I want to use the getInstance(boolean newInstance) method to generate a new object or reuse the existing singleton object.
if newInstance is true: I will generate a new singleton object
if newInstance is false: if myObject is null, then generate a new one and return, or if myObject is not null, just return it.
And this getInstance(boolean newInstance) must be thread safe. Any idea how?
According to your comment, this is one way to implement what you want:
public class MyObjectFactory {
private volatile MyObject inst;
public synchronized MyObject getInstance(boolean newInstance) {
if(newInstance) {
inst = new MyObject(...);
}
return inst;
}
}
Making the field volatile means that the value is not cached in the CPU, so changes are immediately visible to all threads. Making the method synchronized ensures that only one thread can enter it at the same time.
This is not how Singletons work. The whole point of a Singleton is to have a single instance across the program of a certain class. Parameterizing your factory method to either get a new instance or a previous one does not fall into the definition of a Singleton.
Also, the best Singleton implementation is known as the Bill Pugh Singleton:
public class BillPughSingleton {
private BillPughSingleton() {}
public static BillPughSingleton getInstance() {
return SingletonHelper.INSTANCE;
}
private static class SingletonHelper {
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
}
The William Pugh implementation ensures multi-thread safety and the best performances as the nested static class is loaded by the class loader only when the method getInstance() is invoked. In fact, a static nested class is simply a static member of the outer class (no difference from a static field or a static method in terms of creation time). The static member is created only when the class is used, so since no instances of the BillPughSingleton can be created with a constructor, a single thread-safe instance is generated only when the outer class is used via the getInstance() method.
EDIT
If what you're asking is something that either creates a new instance if this is null or returns/overrides the existing one. Then, what you need is not a singleton but a retriever class. Besides, you should also take into consideration in your design whether this retriever class will be used in multi-thread scenarios or not. Here is a basic implementation:
class MyRetriever {
private static MyClass instance;
//Private constructor to force the factory method invocation
private MyRetriever() {}
//Synchronizing the method in order to avoid race condition and establish a happens-before relationship between threads
public synchronized static MyClass getInstance(boolean flagOverride) {
if (flagOverride || instance == null){
instance = new MyClass();
}
return instance;
}
}

Singleton contract using inheritance?

I'm trying to create a framework where Singleton objects can get the core of their implementation from. The use for this is so if I make multiple Singleton classes, I don't need to re-write their (while simple) implementations over and over.
I tried this:
public abstract class Singleton
{
protected static final Lock mutex = new ReentrantLock(true);
// Not even subclasses are allowed to mess with `instance`.
private static Singleton instance = null;
// Here is the problem, static methods cannot be abstract.
protected static abstract Singleton init();
public static Singleton get()
{
mutex.lock();
// The super class has no idea how to instantiate
// this singleton, so let subclasses handle that
// via the abstract init method
if (instance == null)
instance = init();
mutex.unlock();
return instance;
}
}
But it really cannot work because the whole concept of static members with inheritance doesn't go well together.
My other option is to do:
public enum Singleton
{
INSTANCE
}
But since enum cannot be extended, I cannot do:
public enum MySingleton extends Singleton
{
// Member variables and functions here
...
}
I could have every implementation just be an enum and the only code I have to repeat (I think?) is INSTANCE unless I'm missing something? The only downside I see there is the Singleton is created at the beginning of the runtime and not on-demand later on in the program.
I could also do an interface but then I get stuck here:
public interface Singleton
{
Singleton instance = null;
default void set(Singleton s)
{
assert instance == null;
assert s != null;
// cannot do this, as `instance` is FINAL
instance = s;
}
}
What's the best way to do define a Singleton contract without having to retype the entire implementation over again?
Thanks

When does Java enum initialize? [duplicate]

In Java we can do the following to initialize class and call method inside that class:
public class MyClass {
public String myClassMethod() {
return "MyClass";
}
}
.
public class Test {
public static void main(String[] args) {
MyClass myClass = new MyClass(); // initialize MyClass
myClass.myClassMethod();// call a method
}
}
If my class is an enum class, implementation will be the following:
public enum MyEnumClass {
INSTANCE;
public String myEnumClassMethod() {
return "MyEnumClass";
}
}
.
public class Test {
public static void main(String[] args) {
MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
myEnumClass.myEnumClassMethod();
}
}
Both of these cases works in the same way, but it is said to be better in the enum implementation. My question is why and how it is happening?
An enum is essentially a singleton pattern.
The JVM handles the initialization and storage of enum instances. To see this most clearly you can write:
public enum MyEnumClass {
INSTANCE("some value for the string.");
private final String someString;
private MyEnumClass(final String someString) {
this.someString = someString;
}
public String getSomeString(){
return someString;
}
}
And in another class:
public static void main(String[] args) {
final MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
system.out.println(myEnumClass.getSomeString());
}
This would print out "some value for the string.".
This demonstrates that the enum instances are initialised at class load time, i.e. as if by the static initialiser.
Or put another way:
new MyClass() == new MyClass();
Is always false, whereas:
MyEnumClass.INSTANCE == MyEnumClass.INSTANCE;
Is always true. i.e. MyEnumClass.INSTANCE is always the same MyEnumClass.INSTANCE whereas a new MyClass is created every time your call new MyClass().
This brings us nicely to your question of "better".
An enum is a singleton instance with various nifty methods for converting String enum names into a reference to the singleton instance that it represents. It also guarantees that if you de-serialize an enum there won't be two separate instances like there would for a normal class.
So an enum is certainly much better as a robust and threadsafe singleton than a class.
But we cannot have two instances of INSTANCE with the different values for someString so the enum is useless as a class...
In short enums are good for what they're good for and classes are good for what they're good for. They are not substitutes and therefore cannot be compared in any meaningful way expect when one is used as the other.
It's a simple implementation of the Singleton pattern, relying on the mechanisms of how Enum's work.
If you use MyEnumClass.INSTANCE a second time, you'll get the same object instance.
In contrast, new MyClass(); will create a new object.
See also discussion here:
What is the best approach for using an Enum as a singleton in Java?
There would possibly be more to learn by reading Java Language Spec Section 8-9

If not for lazy initialisation, is there any advantage of building singleton using method rather than static class member?

Very often I see singleton built in this way:
public static MyClass instance() {
if (singleton == null) {
singleton = new MyClass();
}
return singleton;
}
If not for the lazy initialization effect, does the approach have any advantage over simply declaring a static instance like this?
public final static MyClass singleton = new MyClass();
No, in fact the other approach, i.e.:
public final static MyClass singleton = new MyClass();
might be better as, if you you have 2 threads calling the instance method at the same time you could get a race condition.
This is how Java in Practice says to do singletons:
private final static MyClass _instance = new MyClass();
public static MyClass getInstance() {
return _instance;
}
private MyClass() {}
Update Since #jon-skeet mentioned it there is really good discussion of Singletons in the book Effective Java by Joshua Block. One thing he points out is that if you want your Singleton to be serializable you can't just implement Serializable. You need to override the readResolve method as well. Use the above approach makes this easy:
private Object readResolve() throws ObjectStreamException {
return _instance;
}
Update 2: Checkout this excellent discussion on Singletons linked to by #mardavi: http://en.wikipedia.org/wiki/Singleton_pattern#Initialization_On_Demand_Holder_Idiom

Hiding the visibility of a class to other classes

Basically I have a class which an instance of is created via a Singleton class. The class should never been instantiated via any other means than the singleton class. My question is can the class be effectively 'not seen' by other classes, apart from Singleton.
I know inner classes and different pacakages etc would help, but I'm curious to see if anyone has a nice solution to this.
Thanks for replies
Just refactor class itself as singleton. Private constructor and etc.
An easy and efficient way to do Singleton with an Enum:
public enum Singleton {
INSTANCE;
public void execute (String arg) {
//... perform operation here ...
}
}
In a sample scenario, using your API, do I need to declare?:
ToBeInvisibleClass instance = TheSingleton.getThatInvisibleInstnace();
If the answer is Yes, then the answer to your question is No since I need to declare a variable and for that I need the type to visible. If the answer is No, then using inner/nested class seems to be a proper approach or making the class itself the singleton.
Java has no "friend" concept like C++
You mentioned nested classes (real inner classes will not work because they need the outer) and packages.
Other approaches to protected other classes but one from creating an instance are not known to me.
But in general there is no reason to build a singleton by an helper class.
You could build singleton using enums or static final vars
What is the best approach for using an Enum as a singleton in Java?
public enum Elvis implements HasAge {
INSTANCE;
private int age;
#Override
public int getAge() {
return age;
}
}
class X {
public static final X instance = new X ();
private X () {
}
...
}
To assure that instantiation only occurs through your class method, you can do the following:
Make the default constructor private
Save your singleton instance in a private method
Use a public static method to provide the instance to the clients:
In this site there's a nice example:
public class MySingleton {
private static MySingleton _instance = new MySingleton();
private MySingleton() {
// construct object . . .
}
public static MySingleton getInstance() {
return _instance;
}

Categories

Resources