blob: 1772a3c71fc3cb026f17c4dbd80d6f16dc59b5c5 [file] [log] [blame]
Madan Jampaniab6d3112014-10-02 16:30:14 -07001package org.onlab.netty;
2
3import java.util.concurrent.TimeUnit;
4import java.util.concurrent.TimeoutException;
5
6/**
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.
Madan Jampaniab6d3112014-10-02 16:30:14 -070011 */
Madan Jampani53e44e62014-10-07 12:39:51 -070012public class AsyncResponse implements Response {
Madan Jampaniab6d3112014-10-02 16:30:14 -070013
Madan Jampani53e44e62014-10-07 12:39:51 -070014 private byte[] value;
Madan Jampaniab6d3112014-10-02 16:30:14 -070015 private boolean done = false;
16 private final long start = System.nanoTime();
17
18 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -070019 public byte[] get(long timeout, TimeUnit timeUnit) throws TimeoutException {
Madan Jampani938aa432014-10-04 17:37:23 -070020 timeout = timeUnit.toNanos(timeout);
Madan Jampaniab6d3112014-10-02 16:30:14 -070021 boolean interrupted = false;
22 try {
23 synchronized (this) {
24 while (!done) {
25 try {
26 long timeRemaining = timeout - (System.nanoTime() - start);
27 if (timeRemaining <= 0) {
28 throw new TimeoutException("Operation timed out.");
29 }
30 TimeUnit.NANOSECONDS.timedWait(this, timeRemaining);
31 } catch (InterruptedException e) {
32 interrupted = true;
33 }
34 }
35 }
36 } finally {
37 if (interrupted) {
38 Thread.currentThread().interrupt();
39 }
40 }
41 return value;
42 }
43
44 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -070045 public byte[] get() throws InterruptedException {
Madan Jampaniab6d3112014-10-02 16:30:14 -070046 throw new UnsupportedOperationException();
47 }
48
49 @Override
50 public boolean isReady() {
51 return done;
52 }
53
54 /**
55 * Sets response value and unblocks any thread blocking on the response to become
56 * available.
57 * @param data response data.
58 */
Madan Jampani53e44e62014-10-07 12:39:51 -070059 public synchronized void setResponse(byte[] data) {
Madan Jampaniab6d3112014-10-02 16:30:14 -070060 if (!done) {
61 done = true;
Madan Jampani53e44e62014-10-07 12:39:51 -070062 value = data;
Madan Jampaniab6d3112014-10-02 16:30:14 -070063 this.notifyAll();
64 }
65 }
66}