-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompletableFuture.java
More file actions
64 lines (53 loc) · 1.67 KB
/
CompletableFuture.java
File metadata and controls
64 lines (53 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package example7;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class CompletableFuture<T> implements java.util.concurrent.Future<T> {
private boolean _isDone = false;
private T value = null;
private Throwable error = null;
public boolean cancel(boolean mayInterruptIfRunning) {
throw new UnsupportedOperationException();
}
public boolean isCancelled() {
return false;
}
public synchronized boolean isDone() {
return _isDone;
}
public T get() throws InterruptedException, ExecutionException {
try {
return get(10, TimeUnit.DAYS);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
public T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
synchronized (this) {
while (!_isDone)
this.wait(unit.toMillis(timeout));
if (error != null)
if (error instanceof RuntimeException)
throw (RuntimeException) error;
else
throw new RuntimeException(error);
else
return value;
}
}
public synchronized void trySuccess(T value) {
if (!_isDone) {
this.value = value;
this._isDone = true;
this.notifyAll();
}
}
public synchronized void tryFailure(Throwable th) {
if (!_isDone) {
this.error = th;
this._isDone = true;
this.notifyAll();
}
}
}