KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > remoting > ExportTable


1 package hudson.remoting;
2
3 import java.util.HashMap JavaDoc;
4 import java.util.Map JavaDoc;
5
6 /**
7  * Manages unique ID for exported objects, and allows look-up from IDs.
8  *
9  * @author Kohsuke Kawaguchi
10  */

11 final class ExportTable<T> {
12     private final Map JavaDoc<Integer JavaDoc,T> table = new HashMap JavaDoc<Integer JavaDoc,T>();
13     private final Map JavaDoc<T,Integer JavaDoc> reverse = new HashMap JavaDoc<T,Integer JavaDoc>();
14
15     /**
16      * Unique ID generator.
17      */

18     private int iota = 1;
19
20     /**
21      * Exports the given object.
22      *
23      * <p>
24      * Until the object is {@link #unexport(Object) unexported}, it will
25      * not be subject to GC.
26      *
27      * @return
28      * The assigned 'object ID'. If the object is already exported,
29      * it will return the ID already assigned to it.
30      */

31     // TODO: the 'intern' semantics requires reference counting for proper unexport op.
32
public synchronized int export(T t) {
33         if(t==null) return 0; // bootstrap classloader
34

35         Integer JavaDoc id = reverse.get(t);
36         if(id==null) {
37             id = iota++;
38             table.put(id,t);
39             reverse.put(t,id);
40         }
41
42         return id;
43     }
44
45     public synchronized T get(int id) {
46         return table.get(id);
47     }
48
49     /**
50      * Removes the exported object from the table.
51      */

52     public synchronized void unexport(T t) {
53         if(t==null) return;
54         Integer JavaDoc id = reverse.remove(t);
55         if(id==null) return; // presumably already unexported
56
table.remove(id);
57     }
58 }
59
Popular Tags