如何將實現Callable<T>
的子接口的任務提交到ExecutorService
?將執行Callable <T>的子接口的任務提交給ExecutorService
我有Callable<T>
子接口定義爲:
public interface CtiGwTask<T>
extends Callable {
...
}
它只是定義了一些靜態常量,但不會增加的方法。
然後我有以下方法,其中execService
是一個FixedThreadPool
實例。
@Override
public CtiGwTaskResult<Integer> postCtiTask(CtiGwTask<CtiGwTaskResult<Integer>> task) {
Future<CtiGwTaskResult<Integer>> result =
execService.submit(task);
try {
return result.get();
} catch (InterruptedException | ExecutionException ex) {
LOGGER.log(Level.FINEST,
"Could not complete CTIGwTask", ex);
return new CtiGwTaskResult<>(
CtiGwResultConstants.CTIGW_SERVER_SHUTTINGDOWN_ERROR,
Boolean.FALSE,
"Cannot complete task: CTIGateway server is shutting down.",
ex);
}
}
不幸的是,這是給予2未經檢查的轉換和1未經檢查的方法調用警告。
...\CtiGwWorkerImpl.java:151: warning: [unchecked] unchecked conversion
execService.submit(task);
required: Callable<T>
found: CtiGwTask<CtiGwTaskResult<Integer>>
where T is a type-variable:
T extends Object declared in method <T>submit(Callable<T>)
...\CtiGwWorkerImpl.java:151: warning: [unchecked] unchecked method invocation: method submit in interface ExecutorService is applied to given types
execService.submit(task);
required: Callable<T>
found: CtiGwTask<CtiGwTaskResult<Integer>>
where T is a type-variable:
T extends Object declared in method <T>submit(Callable<T>)
...\CtiGwWorkerImpl.java:151: warning: [unchecked] unchecked conversion
execService.submit(task);
required: Future<CtiGwTaskResult<Integer>>
found: Future
如果我改變submit
調用
Future<CtiGwTaskResult<Integer>> result =
execService.submit((Callable<CtiGwTaskResult<Integer>>) task);
然後一切似乎工作,但現在我得到一個unchecked投警告。
...\src\com\dafquest\ctigw\cucm\CtiGwWorkerImpl.java:151: warning: [unchecked] unchecked cast
execService.submit((Callable<CtiGwTaskResult<Integer>>) task);
required: Callable<CtiGwTaskResult<Integer>>
found: CtiGwTask<CtiGwTaskResult<Integer>>
所以我錯過了什麼? submit()
不適用於Callable子類的實例嗎?
如果此'未來>結果= execService.submit((可贖回>)任務);'給你一個''cast''警告,爲什麼不嘗試'Future > result =(Future >)execService.submit((Callable >)task);''你也可以發佈,如果你嘗試過這樣的東西。 –
DaGLiMiOuX
嘗試了很多我不記得但我只是測試,因爲我懷疑沒有變化。警告是指'(Callable>)任務'cast,但一旦應用返回類型和方法調用不再是「未選中」。 –
AndRAM