假設我們有可能長時間運行的任務:裝飾Java的調用添加行爲
public class LongRunningTask {
public ReturnType doSomething() {
...
}
}
而且我們希望同時運行許多任務。
所以,我有我的調用它:
public class LongRunningCallable implements Callable<LongRunningTask> {
private final LongRunningTask task;
...
public ReturnType call() {
return task.doSomething();
}
...
}
現在,因爲這可能真的持續多久,我minght要限制它只有一定量的運行。所以,我可能會做這樣的事情:
public class InterruptibleCallable<T> implements Callable<T> {
protected final long timeout;
protected final TimeUnit timeUnit;
protected final Callable<T> callable;
public InterruptibleCallable(long timeout, TimeUnit timeUnit, Callable<T> callable) {
this.timeout = timeout;
this.timeUnit = timeUnit;
this.callable = callable;
}
@Override
public T call() throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
T result = null;
try {
result = executorService.submit(callable).get(timeout, timeUnit);
} catch (InterruptedException e) {
LOGGER.error("Callable: " + callable.toString() + " was interrupted");
throw e;
} catch (ExecutionException e) {
throw e;
} catch (TimeoutException e) {
LOGGER.warn("Callable: " + callable.toString() + " timed out after " + timeout + " " + timeUnit);
throw e;
} finally {
executorService.shutdown();
}
return result;
}
}
這是確定的,但現在我也想換行,以便它可以重試本身(有延遲),如果它encounteres異常:
public class RetryableCallable<T> implements Callable<T> {
private final long delay;
private final TimeUnit timeUnit;
private final Callable<T> callable;
@Override
public T call() throws Exception {
T result = null;
try {
ExecutorService executorService = Executors.newSingleThreadExecutor();
result = executorService.submit(this.callable).get();
} catch (Exception e) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
result = executorService.schedule(this.callable, delay, timeUnit).get();
}
return result;
}
}
現在,我的問題(S):
是否已有此capabilites的提供該庫(或超集)?
這是一個很好的設計,尤其是創建另一個執行器並在每個包裝器中提交一個可調用對象,爲什麼?
從設計模式視圖和性能視圖兩方面處理此問題的最佳方法是什麼?
謝謝:d
爲什麼要在其名稱中具有「可調用」的類創建新的線程池?這聽起來太複雜了。 –