blob: b2b490e88fd793256ea9980253e3fe5cde3f1dd8 [file] [log] [blame]
Madan Jampanic9ed9be2014-10-02 16:13:11 -07001package org.onlab.netty;
Madan Jampani890bc352014-10-01 22:35:29 -07002
3import java.util.concurrent.TimeUnit;
4import java.util.concurrent.TimeoutException;
5
Madan Jampani890bc352014-10-01 22:35:29 -07006/**
7 * An asynchronous response.
8 * This class provides a base implementation of Response, with methods to retrieve the
9 * result and query to see if the result is ready. The result can only be retrieved when
10 * it is ready and the get methods will block if the result is not ready yet.
11 * @param <T> type of response.
12 */
13public class AsyncResponse<T> implements Response<T> {
14
15 private T value;
16 private boolean done = false;
17 private final long start = System.nanoTime();
18
19 @Override
20 public T get(long timeout, TimeUnit tu) throws TimeoutException {
21 timeout = tu.toNanos(timeout);
22 boolean interrupted = false;
23 try {
24 synchronized (this) {
25 while (!done) {
26 try {
27 long timeRemaining = timeout - (System.nanoTime() - start);
28 if (timeRemaining <= 0) {
29 throw new TimeoutException("Operation timed out.");
30 }
31 TimeUnit.NANOSECONDS.timedWait(this, timeRemaining);
32 } catch (InterruptedException e) {
33 interrupted = true;
34 }
35 }
36 }
37 } finally {
38 if (interrupted) {
39 Thread.currentThread().interrupt();
40 }
41 }
42 return value;
43 }
44
45 @Override
46 public T get() throws InterruptedException {
47 throw new UnsupportedOperationException();
48 }
49
50 @Override
51 public boolean isReady() {
52 return done;
53 }
54
55 /**
56 * Sets response value and unblocks any thread blocking on the response to become
57 * available.
58 * @param data response data.
59 */
60 @SuppressWarnings("unchecked")
61 public synchronized void setResponse(Object data) {
62 if (!done) {
63 done = true;
64 value = (T) data;
65 this.notifyAll();
66 }
67 }
68}