KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com4j > util > ComObjectCollector


1 package com4j.util;
2
3 import com4j.Com4jObject;
4 import com4j.ComObjectListener;
5
6 import java.util.Map JavaDoc;
7 import java.util.WeakHashMap JavaDoc;
8
9 /**
10  * {@link ComObjectListener} implementation that collects all
11  * newly created {@link Com4jObject}s
12  *
13  * <p>
14  * The intended use of this class is to record objects created
15  * in a certain block and then dipose them all (except a few marked explicitly)
16  * at once at some later point.
17  *
18  * <p>
19  * See the following code example for a typical usage:
20  * <pre>
21  * <pre class=code>
22     void foo() {
23         // we will start using COM objects.
24         // so we'll register the listener and start keeping
25         // track of COM objects we create.
26         ComObjectCollector col = new ComObjectCollector();
27         COM4J.addListener(col);
28
29         try {
30             // use COM objects as much as you want
31             IFoo foo = doALotOfComStuff();
32
33             // do this to avoid COM objects from disposed by the diposeAll method.
34             col.remove(foo);
35         } finally {
36             // dipose all the COM objects created in this thread
37             // since the listener is registered.
38             // But "foo" won't be diposed because of the remove method.
39             col.disposeAll();
40
41             // make sure to remove the listener
42             COM4J.removeListener(col);
43         }
44     }
45  *</pre>
46  *
47  * @author Kohsuke Kawaguchi (kk@kohsuke.org)
48  */

49 public class ComObjectCollector implements ComObjectListener {
50     protected final Map JavaDoc<Com4jObject,Object JavaDoc> objects = new WeakHashMap JavaDoc<Com4jObject,Object JavaDoc>();
51
52     public void onNewObject(Com4jObject obj) {
53         objects.put(obj,null);
54     }
55
56     /**
57      * Removes the given object from the list of {@link Com4jObject}s that
58      * this class keeps.
59      *
60      * <p>
61      * If the application knows certain {@link Com4jObject} needs to live after
62      * the {@link #diposeAll()} method, this method can be called to avoid the object
63      * from being disposed.
64      *
65      * <p>
66      * If the object passed in is not known to this {@link ComObjectCollector},
67      * it is a no-op.
68      */

69     public void remove(Com4jObject obj) {
70         objects.remove(obj);
71     }
72
73     /**
74      * Calls the {@link Com4jObject#dispose()} method for all the {@link Com4jObject}s
75      * known to this {@link ComObjectCollector}.
76      *
77      * <p>
78      * Each time this method is called, it forgets all the diposed objects.
79      */

80     public void diposeAll() {
81         for( Com4jObject o : objects.keySet() )
82             o.dispose();
83         objects.clear();
84     }
85 }
86
Popular Tags