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