use*_*860 9 java generics object-pooling
我如何InternPool<T>用Java 编写泛型?它需要一个Internable界面吗?
String在Java中有实习能力; 我想要像BigDecimal和的实习班Account.
像这样的东西:
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元素类,equals并hashCode提供"按值相等"并遵守这些方法的API契约.但BigDecimal肯定会.
更新 - 为了解释为什么我们需要一个WeakHashMap<T, WeakReference<T>>而不是一个WeakHashMap<T, T>,请参阅javadocs.简短版本是后者中的关键弱链接不会被GC破坏,因为相应的条目引用使得值可以很容易地到达.