user1603602
user1603602

Reputation: 974

Java How to destroy Singleton instance

I have a singleton that is created like that

private static class SingletonHolder { 
    public static Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
    return SingletonHolder.INSTANCE;
}

I'd like to reset the singleton instance at a certain time. (I'm sure at this time it is safe to reset the singleton instance). I tried to remove the final specifier and set the instance to null when I want to reset it but the problem is how to get another instance (It will remain null)

Another question is is it safe to remove the final specifier inside the SingletonHolder.

Thanks

Upvotes: 7

Views: 25998

Answers (2)

user2511414
user2511414

Reputation:

you would provide a package-visible(default access level) method for other classes to be able to reset the singleton, something like this

class SingleGuy{
 private static SingleGuy=new SingleGuy();//eager init mode
 synchronized static void initTheGuy(){
  SingleGuy=new SingleGuy();//while this not recommended!
 }
 synchronized static void resetTheInstance(){
  /*Reset the singleton state as you wish. just like you reinitialized*/
 } 
}

Upvotes: 2

Polentino
Polentino

Reputation: 907

If you really need to reset a singleton instance (which doesn't makes much sense actually) you could wrap all its inner members in a private object, and reinitialize via an explicit initialize() and reset() methods. That way, you can preserve your singleton istance and provide some kind of "reset" functionality.

Upvotes: 5

Related Questions