async timeout for CacheResult
package com.alicp.jetcache;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionStage;
-import java.util.concurrent.ExecutionException;
+import java.time.Duration;
+import java.util.concurrent.*;
/**
* Created on 2016/9/28.
@@ -23,6 +22,9 @@ public class CacheResult {
private String message;
private CompletionStage<ResultData> future;
+ private static Duration DEFAULT_TIMEOUT = Duration.ofMillis(500);
+ private Duration timeout = DEFAULT_TIMEOUT;
+
public CacheResult(CompletionStage<ResultData> future) {
this.future = future;
}
@@ -44,9 +46,10 @@ public class CacheResult {
return;
}
try {
- ResultData resultData = future.toCompletableFuture().get();
+ ResultData resultData = future.toCompletableFuture().get(
+ timeout.toMillis(), TimeUnit.MILLISECONDS);
fetchResultSuccess(resultData);
- } catch (InterruptedException | ExecutionException e) {
+ } catch (TimeoutException | InterruptedException | ExecutionException e) {
fetchResultFail(e);
}
}
@@ -74,4 +77,12 @@ public class CacheResult {
public CompletionStage<ResultData> future() {
return future;
}
+
+ public static void setDefaultTimeout(Duration defaultTimeout) {
+ DEFAULT_TIMEOUT = defaultTimeout;
+ }
+
+ public void setTimeout(Duration timeout) {
+ this.timeout = timeout;
+ }
}
