Java中的通用InternPool <T>?

use*_*860 9 java generics object-pooling

我如何InternPool<T>用Java 编写泛型?它需要一个Internable界面吗?

String在Java中有实习能力; 我想要像BigDecimal和的实习班Account.

Ste*_*n C 5

像这样的东西:

public class InternPool<T> {

    private WeakHashMap<T, WeakReference<T>> pool = 
        new WeakHashMap<T, WeakReference<T>>();

    public synchronized T intern(T object) {
        T res = null;
        // (The loop is needed to deal with race
        // conditions where the GC runs while we are
        // accessing the 'pool' map or the 'ref' object.)
        do {
            WeakReference<T> ref = pool.get(object);
            if (ref == null) {
                ref = new WeakReference<T>(object);
                pool.put(object, ref);
                res = object;
            } else {
                res = ref.get();
            }
        } while (res == null);
        return res;
    }
}
Run Code Online (Sandbox Code Playgroud)

这取决于实现的pool元素类,equalshashCode提供"按值相等"并遵守这些方法的API契约.但BigDecimal肯定会.


更新 - 为了解释为什么我们需要一个WeakHashMap<T, WeakReference<T>>而不是一个WeakHashMap<T, T>,请参阅javadocs.简短版本是后者中的关键弱链接不会被GC破坏,因为相应的条目引用使得值可以很容易地到达.


fin*_*nnw 5

举一个例子来看一看Interner来自番石榴。它不是需要一个Internable接口,它只是依赖于equalshashCode


Bal*_*usC 3

这听起来更像是您正在寻找蝇量级模式

Flyweight是一种软件设计模式。享元是一种通过与其他类似对象共享尽可能多的数据来最小化内存使用的对象

单击该链接,它包含一个 Java 示例。