27
27
import java .util .concurrent .TimeUnit ;
28
28
import java .util .concurrent .TimeoutException ;
29
29
30
+ import org .slf4j .Logger ;
31
+ import org .slf4j .LoggerFactory ;
32
+
30
33
/**
31
34
* A really simplified implementation of future that allows completing it successfully with a value
32
35
* or exceptionally with an exception.
33
36
*/
34
37
class PromiseSupport <T > implements Future <T > {
38
+
39
+ private static final Logger LOGGER = LoggerFactory .getLogger (PromiseSupport .class );
35
40
36
41
private static final int RUNNING = 1 ;
37
42
private static final int FAILED = 2 ;
@@ -80,40 +85,34 @@ public boolean isDone() {
80
85
81
86
@ Override
82
87
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 ) {
89
90
lock .wait ();
90
- if (state == COMPLETED ) {
91
- return value ;
92
- } else {
93
- throw new ExecutionException (exception );
94
- }
95
91
}
96
92
}
93
+ if (state == COMPLETED ) {
94
+ return value ;
95
+ }
96
+ throw new ExecutionException (exception );
97
97
}
98
98
99
99
@ Override
100
100
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 ();
115
109
}
116
110
}
117
111
}
112
+
113
+ if (state == COMPLETED ) {
114
+ return value ;
115
+ }
116
+ throw new ExecutionException (exception );
118
117
}
119
118
}
0 commit comments