diff options
author | toma <toma@283d02a7-25f6-0310-bc7c-ecb5cbfe19da> | 2009-11-25 17:56:58 +0000 |
---|---|---|
committer | toma <toma@283d02a7-25f6-0310-bc7c-ecb5cbfe19da> | 2009-11-25 17:56:58 +0000 |
commit | 90825e2392b2d70e43c7a25b8a3752299a933894 (patch) | |
tree | e33aa27f02b74604afbfd0ea4f1cfca8833d882a /qtjava/javalib/org/kde/qt/WeakValueMap.java | |
download | tdebindings-90825e2392b2d70e43c7a25b8a3752299a933894.tar.gz tdebindings-90825e2392b2d70e43c7a25b8a3752299a933894.zip |
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
Diffstat (limited to 'qtjava/javalib/org/kde/qt/WeakValueMap.java')
-rw-r--r-- | qtjava/javalib/org/kde/qt/WeakValueMap.java | 68 |
1 files changed, 68 insertions, 0 deletions
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); + } + } +} |