From 90825e2392b2d70e43c7a25b8a3752299a933894 Mon Sep 17 00:00:00 2001 From: toma Date: Wed, 25 Nov 2009 17:56:58 +0000 Subject: Copy the KDE 3.5 branch to branches/trinity for new KDE 3.5 features. BUG:215923 git-svn-id: svn://anonsvn.kde.org/home/kde/branches/trinity/kdebindings@1054174 283d02a7-25f6-0310-bc7c-ecb5cbfe19da --- qtjava/javalib/org/kde/qt/WeakValueMap.java | 68 +++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 qtjava/javalib/org/kde/qt/WeakValueMap.java (limited to 'qtjava/javalib/org/kde/qt/WeakValueMap.java') diff --git a/qtjava/javalib/org/kde/qt/WeakValueMap.java b/qtjava/javalib/org/kde/qt/WeakValueMap.java new file mode 100644 index 00000000..4378b7e2 --- /dev/null +++ b/qtjava/javalib/org/kde/qt/WeakValueMap.java @@ -0,0 +1,68 @@ +/** From Section 12.5.3, Reference Queues page 324-326 + of 'The Java Programming Language, Third Edition'. + + But why wasn't it included in the java.util Collection package? + */ + + +package org.kde.qt; + +import java.lang.ref.*; +import java.util.*; + +public class WeakValueMap extends HashMap { + private ReferenceQueue reaped = new ReferenceQueue(); + + private static class ValueRef extends WeakReference { + private final Object key; // key for value + + ValueRef(Object val, Object key, ReferenceQueue q) { + super(val, q); + this.key = key; + } + } + + public Object put(Object key, Object value) { + reap(); + ValueRef vr = new ValueRef(value, key, reaped); + return super.put(key, vr); + } + + public Object get(Object key) { + reap(); + ValueRef vr = (ValueRef) super.get(key); + if (vr == null) { + return null; + } else { + return vr.get(); + } + } + + /** Force an entry to be removed if it is known to be invalid, + rather than waiting for the garbage collector to put it + on the reaped queue. + */ + public Object remove(Object key) { + reap(); + ValueRef vr = (ValueRef) super.get(key); + if (vr == null) { + return null; + } else { + vr.clear(); + super.remove(key); + return null; + } + } + + public int size() { + reap(); + return super.size(); + } + + public void reap() { + ValueRef ref; + while ((ref = (ValueRef) reaped.poll()) != null) { + super.remove(ref.key); + } + } +} -- cgit v1.2.1