KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > ubik > rmi > server > command > ResponseQueue


1 package org.sapia.ubik.rmi.server.command;
2
3 import org.sapia.ubik.net.Timer;
4
5 import java.util.*;
6
7
8 /**
9  * This class implements a client-side response queue that internally
10  * keeps response locks.
11  *
12  * @author Yanick Duchesne
13  * <dl>
14  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2003 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
15  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
16  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
17  * </dl>
18  */

19 public class ResponseQueue {
20   private static ResponseQueue _instance = new ResponseQueue();
21   private Map _responses = Collections.synchronizedMap(new HashMap());
22   private boolean _shutdown;
23
24   /**
25    * Constructor for ResponseQueue.
26    */

27   ResponseQueue() {
28     super();
29   }
30
31   /***
32    * Creates a response lock and returns it (internally maps the response
33    * lock to an unique identifier which is also assigned to the lock.
34    *
35    * @return a <code>ResponseLock</code>.
36    */

37   public synchronized ResponseLock createResponseLock() {
38     ResponseLock lock = new ResponseLock(this);
39
40     if (_responses.get(lock.getId()) != null) {
41       throw new IllegalStateException JavaDoc("response lock already exists for: " +
42         lock.getId());
43     }
44
45     _responses.put(lock.getId(), lock);
46
47     return lock;
48   }
49
50   /**
51    * This method is called to notify this queue about incoming
52    * responses.
53    *
54    * @param responses a <code>List</code> of <code>Response</code> instances.
55    */

56   public void onResponses(List responses) {
57     Response resp;
58     ResponseLock lock;
59
60     for (int i = 0; i < responses.size(); i++) {
61       resp = (Response) responses.get(i);
62       lock = (ResponseLock) _responses.get(resp.getId());
63
64       if (lock != null) {
65         lock.setResponse(resp.get());
66       }
67     }
68   }
69
70   public synchronized void shutdown(long timeout) throws InterruptedException JavaDoc {
71     _shutdown = true;
72
73     Timer timer = new Timer(timeout);
74
75     while (_responses.size() > 0) {
76       wait(timeout);
77
78       if (timer.isOver()) {
79         break;
80       }
81     }
82   }
83
84   public int size() {
85     return _responses.size();
86   }
87
88   synchronized void removeLock(String JavaDoc id) {
89     _responses.remove(id);
90
91     if (_shutdown) {
92       notify();
93     }
94   }
95
96   /**
97    * Returns this queue class' singleton.
98    *
99    * @return a <code>ResponseQueue</code>.
100    */

101   public static final ResponseQueue getInstance() {
102     return _instance;
103   }
104 }
105
Popular Tags