Java 如何销毁单例实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19210945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:05:26  来源:igfitidea点击:

Java How to destroy Singleton instance

javasingleton

提问by user1603602

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)

我想在某个时间重置单例实例。(我确定此时重置单例实例是安全的)。当我想重置它时,我尝试删除最终说明符并将实例设置为 null 但问题是如何获取另一个实例(它将保持为 null)

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

另一个问题是删除 SingletonHolder 中的最终说明符是否安全。

Thanks

谢谢

采纳答案by Polentino

If you reallyneed 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.

如果您真的需要重置一个单例实例(实际上没有多大意义),您可以将其所有内部成员包装在一个私有对象中,并通过显式initialize()reset()方法重新初始化。这样,您可以保留单例实例并提供某种“重置”功能。

回答by Polentino

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*/
 } 
}