-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSynchronous.java
More file actions
62 lines (52 loc) · 1.89 KB
/
Copy pathSynchronous.java
File metadata and controls
62 lines (52 loc) · 1.89 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
// SPDX-FileCopyrightText: 2018-present Open Networking Foundation
// SPDX-FileCopyrightText: 2022-present Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
package io.atomix;
import com.google.common.base.Throwables;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* DistributedPrimitive that is a synchronous (blocking) version of
* another.
*/
public abstract class Synchronous<S extends SyncPrimitive<S, A>, A extends AsyncPrimitive<A, S>> implements SyncPrimitive<S, A> {
private final A primitive;
protected final Duration operationTimeout;
protected Synchronous(A primitive, Duration operationTimeout) {
this.primitive = checkNotNull(primitive, "primitive cannot be null");
this.operationTimeout = operationTimeout;
}
@Override
public String name() {
return primitive.name();
}
@Override
public void close() {
complete(primitive.close());
}
protected <T> T complete(CompletableFuture<T> future) {
if (operationTimeout == null) {
return future.join();
}
try {
return future.get(operationTimeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
Throwable cause = Throwables.getRootCause(e);
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else {
throw new RuntimeException(cause);
}
}
}
}