[英]Make instance of Singleton Class object eligible for GC
一种选择是在枚举的静态初始化器中完成所有这些操作。 在枚举本身中保留一个静态字段,编写一个私有的静态方法来获取文件的内容,如有必要,读取它,然后在枚举初始化结束时(在静态初始化程序块中)将其设置为null:
public enum Foo {
VALUE1, VALUE2, VALUE3;
private static JAXBReader singleReader;
static {
singleReader = null; // Don't need it any more
}
private Foo() {
JAXBReader reader = getReader();
// Use the reader
}
private static JAXBReader getReader() {
// We don't need to worry about thread safety, as all of this
// will be done in a single thread initializing the enum
if (singleReader == null) {
// This will only happen once
singleReader = new JAXBReader(...);
}
return singleReader;
}
}
这样,只有枚举才知道读取器是一个单例-您仍然可以JAXBReader
在外部喜欢时创建一个新的JAXBReader
,这对于测试非常有用。
(我对于枚举初始化需要外部资源感到有些紧张,但是我可以看到它很难避免。)
使用WeakReference来保存对象。
private static WeakReference<JAXBReader> instance = null;
public static JAXBReader getInstance() {
if (instance.get() == null) {
instance = new WeakReference(new JAXBReader());
}
return instance.get();
}
这样,如果不存在其他参考,它将被GC化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.