Last active
November 15, 2019 16:10
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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