Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid multiple instances of Singleton? [duplicate]

I believe when a singleton object gets serialized and is then deserialized upon a plethora of times in series, there are multiple instances of singletons created.

How can you avoid such a situation?

like image 516
user3761301 Avatar asked Jun 20 '14 20:06

user3761301


People also ask

How can you prevent cloning of a singleton object?

Prevent Singleton Pattern From Cloning To overcome the above issue, we need to implement/override the clone() method and throw an exception CloneNotSupportedException from the clone method. If anyone tries to create a clone object of Singleton , it will throw an exception, as shown in the below code.

Can singleton have multiple instances?

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

What happens if I clone singleton object?

The object cloning is a way to create exact copy of an object. So if somebody will clone our singleton instance, it will create another copy of the Singleton instance which violates principle of Singleton Design Pattern.

How can you avoid multithreading conflict issues by using singleton?

Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.


1 Answers

Normally, when you are creating a Singleton, you make sure that there is only one instance of it. you could do it that way:

public static class Singleton{
    private final static Singleton instance;

    private Singleton(){}

    public static Singleton getInstance(){
        if(instance == null)
            instance = new Singleton();
        return instance;
    }


}

Putting the constructor to private makes sure that no one except this class can create an instance of Singleton.

You only need to call the Singleton with getInstance and the Singleton do all the work on its side.

like image 63
TyMarc Avatar answered Oct 10 '22 21:10

TyMarc