我正在嘗試使用遞回方法實作重試機制。盡管該方法已經回傳了串列,但連續的代碼行也會被執行。

我確信我錯過了一些非常明顯的東西,訓練有素的眼睛可以在一秒鐘內發現。我怎樣才能重做遞回,所以我擺脫了最后一條return null陳述句。它根本不需要。
這是整個代碼:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Retryer {
private static final int RETRY_COUNT = 3;
private static final long RETRY_DELAY = 2; // in seconds
private static int tryCounter = 0;
public Retryer() {}
public void execute() {
List<String> downloadedFiles;
try {
Callable<List<String>> c = new AsyncFileDownloader();
downloadedFiles = c.call();
} catch (Exception e) {
System.out.println("Ops! Starting retry");
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
downloadedFiles = retry(scheduledExecutorService, 0);
System.out.println("Retry ended");
if (downloadedFiles == null || downloadedFiles.isEmpty()) {
System.out.println("Sorry. Will exit now");
System.exit(0);
}
}
System.out.println("Finished successfully with " downloadedFiles.size() " in list.");
}
private List<String> retry (ScheduledExecutorService ses, int retryCounter) {
if (retryCounter == RETRY_COUNT) {
System.out.println("Retry limit reached. Exiting");
ses.shutdown();
return null;
}
try {
System.out.println("Retry attempt # " (retryCounter 1) " will start in " RETRY_DELAY " seconds ...");
ScheduledFuture sf = ses.schedule(new AsyncFileDownloader(), RETRY_DELAY, TimeUnit.SECONDS);
List<String> downloadedFiles = (List<String>) sf.get();
ses.shutdown();
System.out.println("In retry. success " downloadedFiles );
return downloadedFiles;
} catch (Exception e) {
System.out.println("--recursive calling");
retry(ses, retryCounter);
}
System.out.println("--returning null!!! This shouldn't happen");
return null;
}
class AsyncFileDownloader implements Callable<List<String>> {
@Override
public List<String> call() throws Exception {
synchronized (this) {
tryCounter ;
System.out.println("--in pull");
if (tryCounter < 3) throw new IOException("Some bad thing happened");
List<String> retList = new ArrayList<>();
retList.add("file1");
retList.add("file1");
return retList;
}
}
}
}
這里的輸出:
--in pull
Ops! Starting retry
Retry attempt # 1 will start in 2 seconds ...
--in pull
--recursive calling
Retry attempt # 2 will start in 2 seconds ...
--in pull
In retry. success [file1, file1]
--returning null!!! This shouldn't happen
Retry ended
Sorry. Will exit now
uj5u.com熱心網友回復:
如果第一次執行進入 catch 塊,則遞回呼叫重試。一旦第二次呼叫回傳,您在第一次呼叫中的 catch 塊之后繼續執行代碼,導致您點擊列印“回傳 null”。
您真正想要的可能是回傳遞回呼叫的值。請記住,它return向呼叫另一個函式的函式回傳一個值,不一定是呼叫鏈中的第一個函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/484769.html
上一篇:是否可以在打字稿中遞回地將一種類似JSON的型別映射到另一種型別?
下一篇:使用同一字典中的鍵擴展dict值
