KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.sapia.ubik.rmi.server.command;
2
3 import org.sapia.ubik.net.Timer;
4
5
6 /**
7  * A client-side lock on which the caller of an asynchronous call-back
8  * waits for the corresponding call-back's response.
9  *
10  * @author Yanick Duchesne
11  * <dl>
12  * <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>
13  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
14  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
15  * </dl>
16  */

17 public class ResponseLock {
18   private static int _count = 0;
19   private Object JavaDoc _response;
20   private ResponseQueue _queue;
21   private String JavaDoc _id;
22   private boolean _ready;
23
24   /**
25    * Constructor for ResponseLock.
26    */

27   ResponseLock(ResponseQueue parent) {
28     _queue = parent;
29     _id = generateId();
30   }
31
32   /**
33    * Returns this lock's unique identifier.
34    *
35    * @return a unique identifier as a <code>String</code>.
36    */

37   public String JavaDoc getId() {
38     return _id;
39   }
40
41   /**
42    * Releases this lock (clears it from memory).
43    */

44   public void release() {
45     _queue.removeLock(_id);
46   }
47
48   /***
49    * Waits for the response of an asynchronous call-back. The caller
50    * will wait for the length of time specified by the given timeout; if
51    * no response comes in before the given timeout, a
52    * <code>ResponseTimeOutException</code> is thrown.
53    *
54    * @param timeout a timeout, in milliseconds.
55    * @throws ResponseTimeOutException if no response comes in before the specified timeout.
56    * @throws InterruptedException if the caller is interrupted while waiting for the response.
57    * @return a response, as an <code>Object</code>.
58    */

59   public synchronized Object JavaDoc waitResponse(long timeout)
60     throws InterruptedException JavaDoc, ResponseTimeOutException {
61     Timer timer = new Timer(timeout);
62
63     while (!_ready) {
64       wait(timeout);
65
66       if (timer.isOver() && !_ready) {
67         release();
68         throw new ResponseTimeOutException();
69       }
70     }
71
72     release();
73
74     return _response;
75   }
76
77   /**
78    * Sets this lock's response.
79    *
80    * @param an <code>Object</code> corresponding to an asynchronous response.
81    */

82   public synchronized void setResponse(Object JavaDoc r) {
83     _response = r;
84     _ready = true;
85     notify();
86   }
87
88   private static synchronized String JavaDoc generateId() {
89     if (_count > 999) {
90       _count = 0;
91     }
92
93     return "" + System.currentTimeMillis() + (_count++);
94   }
95 }
96
Popular Tags