summaryrefslogtreecommitdiffstats
path: root/qtjava/javalib/org/kde/qt/WeakValueMap.java
blob: 4378b7e2f230e4a7688f5b7d6974a95ab1d33cec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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);
		}
	}
}