Skip to content

Instantly share code, notes, and snippets.

@fmerlin
Last active November 15, 2019 16:10
Show Gist options
  • Save fmerlin/318ba93b668d2508ee5b319cf0e54088 to your computer and use it in GitHub Desktop.
Save fmerlin/318ba93b668d2508ee5b319cf0e54088 to your computer and use it in GitHub Desktop.
This pool is used to keep only one version of an object when they are equal
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
/*
* This pool is used to keep only one version of an object when they are equal
* The object is garbage collected when it is no longer used.
* e.g.:
InternPool<Integer> p = new InternPool<>();
Integer a = pool.intern(new Integer(1));
Integer b = pool.intern(new Integer(1));
assert a == b;
*/
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment