- 最後登錄
- 2022-3-29
- 在線時間
- 2 小時
- 註冊時間
- 2016-11-14
- 閱讀權限
- 20
- 精華
- 0
- UID
- 5259514
- 帖子
- 1
- 積分
- 0 點
- 潛水值
- 140 米
| 發表於 2016-11-28 01:52 PM|顯示全部樓層 如果發覺自己無法使用一些功能或出現問題,請按重新整理一次,並待所有網頁內容完全載入後5秒才進行操作。
如果是 lambda expression 的初學者,這一個 retry class 是一個很好的示範。
- import java.util.function.Supplier;
- public class RetryCommand<T> {
- private static final long SLEEP_IN_MS = 1000L;
-
- public static <V> V retry(Supplier<V> function) throws InterruptedException {
- final int RETRY_TIMES = 20;
- final int RETRY_IN_SECONDS = 10;
- return retry(function, RETRY_TIMES, RETRY_IN_SECONDS);
- }
-
- public static <V> V retry(Supplier<V> function, int maxRetries, int waitInSec) throws InterruptedException {
- int retryCounter = 0;
- while (retryCounter < maxRetries) {
- try {
- V returnType = function.get();
- if(returnType instanceof Boolean && ((Boolean) returnType)) {
- return returnType;
- }
- retryCounter++;
- }
- catch (Exception ex) {
- retryCounter++;
-
- if (retryCounter >= maxRetries) {
- break;
- }
- }
-
- Thread.sleep(SLEEP_IN_MS * waitInSec);
- }
-
- throw new RuntimeException("Command failed on all of " + maxRetries + " retries");
- }
- }
複製代碼
用法:
- RetryCommand.retry(() -> isActionSuccessful());
複製代碼
... |
|