使 Singleton Class 对象的实例符合 GC 条件
Make instance of Singleton Class object eligible for GC
我有一个 class JAXBReader
,它使用 jaxb 生成的 classes 保存未编组的 xml 文件。我使用了单例设计,这样我就不需要一次又一次地解组文件。这个 class 的对象(准确地说是未编组的 xml)只需要初始化一个有八个常量的枚举。枚举常量的构造函数使用单例对象来获取它们所需的 xml.
部分
枚举初始化后,我的系统中不需要JAXBReader
的objetc。我怎样才能做到这一点?
我读到 here 可以调用 setter 将 null 分配给静态 singelton 实例,但我不想在外部执行此操作。我想要那个,在枚举初始化后自动为实例分配 null。
我正在使用 Java 1.7
改用 WeakReference 来握住您的物品。
private static WeakReference<JAXBReader> instance = null;
public static JAXBReader getInstance() {
if (instance.get() == null) {
instance = new WeakReference(new JAXBReader());
}
return instance.get();
}
这样,如果没有其他引用存在,它将被 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;
}
}
这样只有 enum 知道 reader 是一个单例 - 你仍然可以在外部随时创建一个新的 JAXBReader
,这可能对测试非常有用。
(我对枚举初始化需要外部资源开始有点紧张,但我知道这可能很难避免。)
我有一个 class JAXBReader
,它使用 jaxb 生成的 classes 保存未编组的 xml 文件。我使用了单例设计,这样我就不需要一次又一次地解组文件。这个 class 的对象(准确地说是未编组的 xml)只需要初始化一个有八个常量的枚举。枚举常量的构造函数使用单例对象来获取它们所需的 xml.
枚举初始化后,我的系统中不需要JAXBReader
的objetc。我怎样才能做到这一点?
我读到 here 可以调用 setter 将 null 分配给静态 singelton 实例,但我不想在外部执行此操作。我想要那个,在枚举初始化后自动为实例分配 null。
我正在使用 Java 1.7
改用 WeakReference 来握住您的物品。
private static WeakReference<JAXBReader> instance = null;
public static JAXBReader getInstance() {
if (instance.get() == null) {
instance = new WeakReference(new JAXBReader());
}
return instance.get();
}
这样,如果没有其他引用存在,它将被 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;
}
}
这样只有 enum 知道 reader 是一个单例 - 你仍然可以在外部随时创建一个新的 JAXBReader
,这可能对测试非常有用。
(我对枚举初始化需要外部资源开始有点紧张,但我知道这可能很难避免。)