KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > versant > core > util > WeakBag


1
2 /*
3  * Copyright (c) 1998 - 2005 Versant Corporation
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  * Versant Corporation - initial API and implementation
11  */

12 package com.versant.core.util;
13
14 import java.util.HashSet JavaDoc;
15 import java.util.List JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.lang.ref.ReferenceQueue JavaDoc;
19 import java.lang.ref.WeakReference JavaDoc;
20 import java.lang.ref.Reference JavaDoc;
21
22 /**
23  * This maintains a bag of weakly referenced objects. The clean method
24  * must be called from time to time to get rid of the objects that the
25  * garbage collector wants to nuke. This class is not synchronized.
26  */

27 public final class WeakBag {
28
29     private HashSet JavaDoc set = new HashSet JavaDoc();
30     private ReferenceQueue JavaDoc refQueue = new ReferenceQueue JavaDoc();
31
32     public WeakBag() {
33     }
34
35     /**
36      * Add o to the bag and return the WeakReference that can be used to
37      * remove it.
38      */

39     public WeakReference JavaDoc add(Object JavaDoc o) {
40         WeakReference JavaDoc ans = new WeakReference JavaDoc(o, refQueue);
41         set.add(ans);
42         return ans;
43     }
44
45     /**
46      * Remove o from the bag.
47      */

48     public void remove(Reference JavaDoc o) {
49         set.remove(o);
50     }
51
52     /**
53      * Get the approximate number of objects in the bag.
54      */

55     public int size() {
56         return set.size();
57     }
58
59     /**
60      * Get all the objects still in the bag.
61      */

62     public List JavaDoc values() {
63         ArrayList JavaDoc a = new ArrayList JavaDoc(set.size());
64         for (Iterator JavaDoc i = set.iterator(); i.hasNext(); ) {
65             WeakReference JavaDoc r = (WeakReference JavaDoc)i.next();
66             Object JavaDoc o = r.get();
67             if (o != null) 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 JavaDoc r = refQueue.poll();
79             if (r == null) return;
80             set.remove(r);
81         }
82     }
83
84 }
85
Popular Tags