次のSSCCEは、サーバーからレコードを取得することを示しています(たとえば)。ExecutorService
を使用してThreadPool
of 2 スレッドを作成し、これらすべてのスレッドをTimeout
of 3 秒で呼び出しました。意図的にいくつかのタスクを失敗させました。
私の質問は、失敗したタスクの EmpID を取得する方法です。
メインクラス:
public class MultiThreadEx {
public static void main(String[] args) {
String[] empIDArray = {
"100", "200", "300", "400", "500",
"600", "700", "800", "900", "1000",
"1100", "1200", "1300", "1400", "1500"
};
List<ThreadTaskEach> taskList = new ArrayList<ThreadTaskEach>();
try {
for(String empID : empIDArray) {
taskList.add(new ThreadTaskEach(empID));
}
} catch(Exception e) {
System.out.println("Exception occured: " + e.getMessage());
}
List<Future<Map<String, String>>> futureList = null;
try {
ExecutorService service = Executors.newFixedThreadPool(2);
futureList = service.invokeAll(taskList, 3, TimeUnit.SECONDS);
service.shutdown();
} catch(InterruptedException ie) {
System.out.println("Exception occured: " + ie.getMessage());
}
for(Future<Map<String, String>> future : futureList) {
try {
Map<String, String> resultMap = future.get();
for(String key : resultMap.keySet()) {
System.out.println(resultMap.get(key));
}
} catch(ExecutionException ee) {
System.out.println("Exception occured: " + ee.getMessage());
} catch (InterruptedException ie) {
System.out.println("Exception occured: " + ie.getMessage());
} catch(CancellationException e) {
System.out.println("Exception occured: " + e.getMessage());
}
}
}
}
スレッドクラス
class ThreadTaskEach implements Callable<Map<String, String>>{
private String empID;
public ThreadTaskEach(String empID) {
this.empID = empID;
}
@Override
public Map<String, String> call() throws Exception {
try {
return prepareMap(empID);
} catch(Exception e) {
System.out.println("Exception occured: " + e.getMessage());
throw new Exception("Exception occured: " + e.getMessage());
}
}
private Map<String, String> prepareMap(String empID) throws InterruptedException {
Map<String, String> map = new HashMap<String, String>();
if(Integer.parseInt(empID) % 500 == 0) {
Thread.sleep(5000);
}
map.put(empID, empID + ": " + Thread.currentThread().getId());
return map;
}
}
上記のコードでは、500、1000 .. が 3 秒以内に完了しません。
Map<String, String> resultMap = future.get();
したがって、これらのタスクに対して future.get() と言うと、 が得られCancellationException
ます。しかし、タスクから EmpID を取得する方法は?