2727import java .util .concurrent .TimeUnit ;
2828import java .util .concurrent .TimeoutException ;
2929
30+ import org .slf4j .Logger ;
31+ import org .slf4j .LoggerFactory ;
32+
3033/**
3134 * A really simplified implementation of future that allows completing it successfully with a value
3235 * or exceptionally with an exception.
3336 */
3437class PromiseSupport <T > implements Future <T > {
38+
39+ private static final Logger LOGGER = LoggerFactory .getLogger (PromiseSupport .class );
3540
3641 private static final int RUNNING = 1 ;
3742 private static final int FAILED = 2 ;
@@ -80,40 +85,34 @@ public boolean isDone() {
8085
8186 @ Override
8287 public T get () throws InterruptedException , ExecutionException {
83- if (state == COMPLETED ) {
84- return value ;
85- } else if (state == FAILED ) {
86- throw new ExecutionException (exception );
87- } else {
88- synchronized (lock ) {
88+ synchronized (lock ) {
89+ while (state == RUNNING ) {
8990 lock .wait ();
90- if (state == COMPLETED ) {
91- return value ;
92- } else {
93- throw new ExecutionException (exception );
94- }
9591 }
9692 }
93+ if (state == COMPLETED ) {
94+ return value ;
95+ }
96+ throw new ExecutionException (exception );
9797 }
9898
9999 @ Override
100100 public T get (long timeout , TimeUnit unit )
101- throws InterruptedException , ExecutionException , TimeoutException {
102- if (state == COMPLETED ) {
103- return value ;
104- } else if (state == FAILED ) {
105- throw new ExecutionException (exception );
106- } else {
107- synchronized (lock ) {
108- lock .wait (unit .toMillis (timeout ));
109- if (state == COMPLETED ) {
110- return value ;
111- } else if (state == FAILED ) {
112- throw new ExecutionException (exception );
113- } else {
114- throw new TimeoutException ();
101+ throws ExecutionException , TimeoutException {
102+ synchronized (lock ) {
103+ while (state == RUNNING ) {
104+ try {
105+ lock .wait (unit .toMillis (timeout ));
106+ } catch (InterruptedException e ) {
107+ LOGGER .warn ("Interrupted!" , e );
108+ Thread .currentThread ().interrupt ();
115109 }
116110 }
117111 }
112+
113+ if (state == COMPLETED ) {
114+ return value ;
115+ }
116+ throw new ExecutionException (exception );
118117 }
119118}
0 commit comments