01: /*
02: * Copyright (c) 1998 - 2005 Versant Corporation
03: * All rights reserved. This program and the accompanying materials
04: * are made available under the terms of the Eclipse Public License v1.0
05: * which accompanies this distribution, and is available at
06: * http://www.eclipse.org/legal/epl-v10.html
07: *
08: * Contributors:
09: * Versant Corporation - initial API and implementation
10: */
11: package com.versant.core.util;
12:
13: import java.util.HashSet;
14: import java.util.List;
15: import java.util.ArrayList;
16: import java.util.Iterator;
17: import java.lang.ref.ReferenceQueue;
18: import java.lang.ref.WeakReference;
19: import java.lang.ref.Reference;
20:
21: /**
22: * This maintains a bag of weakly referenced objects. The clean method
23: * must be called from time to time to get rid of the objects that the
24: * garbage collector wants to nuke. This class is not synchronized.
25: */
26: public final class WeakBag {
27:
28: private HashSet set = new HashSet();
29: private ReferenceQueue refQueue = new ReferenceQueue();
30:
31: public WeakBag() {
32: }
33:
34: /**
35: * Add o to the bag and return the WeakReference that can be used to
36: * remove it.
37: */
38: public WeakReference add(Object o) {
39: WeakReference ans = new WeakReference(o, refQueue);
40: set.add(ans);
41: return ans;
42: }
43:
44: /**
45: * Remove o from the bag.
46: */
47: public void remove(Reference o) {
48: set.remove(o);
49: }
50:
51: /**
52: * Get the approximate number of objects in the bag.
53: */
54: public int size() {
55: return set.size();
56: }
57:
58: /**
59: * Get all the objects still in the bag.
60: */
61: public List values() {
62: ArrayList a = new ArrayList(set.size());
63: for (Iterator i = set.iterator(); i.hasNext();) {
64: WeakReference r = (WeakReference) i.next();
65: Object o = r.get();
66: if (o != null)
67: a.add(o);
68: }
69: return a;
70: }
71:
72: /**
73: * Get rid of objects in the bag that the garbage collector wants to
74: * nuke. This does not block.
75: */
76: public void clean() {
77: for (;;) {
78: Object r = refQueue.poll();
79: if (r == null)
80: return;
81: set.remove(r);
82: }
83: }
84:
85: }
|