[jboss-dev-forums] [Design the new POJO MicroContainer] - Re: Composite Map key and weak reference
bstansberry@jboss.com
do-not-reply at jboss.com
Tue May 20 10:20:40 EDT 2008
I believe Jason's #2 is what I was thinking about in our chat discussion. A rough impl:
| package hacks;
|
| import java.lang.annotation.Annotation;
| import java.lang.ref.Reference;
| import java.lang.ref.ReferenceQueue;
| import java.lang.ref.WeakReference;
|
| public class Key
| {
| private static final ReferenceQueue refQueue = new ReferenceQueue();
|
| private final KeyRef keyRef;
| private final WeakReference<Annotation>[] annotations;
|
| public Key(Class clazz, Annotation[] annotations)
| {
| this.keyRef = new KeyRef(this, clazz, refQueue);
| this.annotations = new WeakReference[annotations.length];
| for (int j = 0; j < annotations.length; j++)
| {
| this.annotations[j]= new WeakReference<Annotation>(annotations[j]);
| }
| }
|
| @Override
| public boolean equals(Object obj)
| {
| if (obj instanceof Key)
| {
| Key other = (Key) obj;
| Class clazz = keyRef.get();
| Class otherClass = other.keyRef.get();
| if (clazz == null || otherClass == null)
| {
| cleanKeyRefs();
| return false;
| }
| else
| {
| if (shouldCleanKeyRefs())
| cleanKeyRefs();
| return clazz.equals(otherClass); // need to add in annotations
| }
| }
|
| return false;
| }
|
| /** Allows optimization; i.e. change to only poll the queue every X invocations */
| private boolean shouldCleanKeyRefs()
| {
| return true;
| }
|
| /**
| * Poll the reference queue and clear the strong ref to Key from all
| * reference objects. This allows the Key to get removed from
| * WeakHashMap.
| */
| private void cleanKeyRefs()
| {
| Reference ref = null;
| while ((ref = refQueue.poll()) != null)
| {
| ((KeyRef) ref).key = null;
| }
| }
|
| private static class KeyRef extends WeakReference<Class>
| {
| private Key key;
|
| KeyRef(Key key, Class clazz, ReferenceQueue queue)
| {
| super(clazz, queue);
| this.key = key;
| }
| }
| }
View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4152029#4152029
Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4152029
More information about the jboss-dev-forums
mailing list