如果出现异常,如何获取原始数据?(How to get reference to original data in case of exceptions?)
我正在使用ExecutorService运行一些Callable线程。 在提交给ExecutorService之前,线程已使用数据初始化。
处理Future.get()抛出的异常时,我想记录一条包含原始数据的消息。 是否有可能从Future对象返回到创建它的原始线程?
伪代码:
void run(List<Data> dataList) { List<Future<Foo>> results = new ArrayList<Future<Foo>>(); for (Data data : dataList) { Callable<Foo> thread = new FooCallable(data); Future<Foo> result = this.executorService.submit(thread); results.add(result); } ... for (Future<Foo> result : results) { Foo foo; try { foo = result.get(); } catch (InterruptedException e) { // // I would like access to the original Data object here // } catch (ExecutionException e) { // // and here // } } }I'm running some Callable threads using ExecutorService. The threads are initialized with data before submitting to ExecutorService.
When handling exceptions thrown by Future.get(), I'd like to log a message with the original data. Is it possible to go from the Future object back to the original thread that created it?
pseudocode:
void run(List<Data> dataList) { List<Future<Foo>> results = new ArrayList<Future<Foo>>(); for (Data data : dataList) { Callable<Foo> thread = new FooCallable(data); Future<Foo> result = this.executorService.submit(thread); results.add(result); } ... for (Future<Foo> result : results) { Foo foo; try { foo = result.get(); } catch (InterruptedException e) { // // I would like access to the original Data object here // } catch (ExecutionException e) { // // and here // } } }最满意答案
使用地图而不是列表存储期货及其相应的数据,并将期货作为关键字用于该地图:
Map<Future<Foo>,Data> results = new HashMap<Future<Foo>,Data>(); for (Data data : dataList) { Callable<Foo> thread = new FooCallable(data); Future<Foo> result = this.executorService.submit(thread); results.put(result,data); } Iterator<Map.Entry<Future<Foo>,Data>> resultsIterator = results.entrySet().iterator(); while(resultsIterator.hasNext()) { Map.Entry<Future<Foo>,Data> entry = resultsIterator.next(); Future<Foo> future = entry.getKey(); Data data = entry.getValue(); Foo foo; try { foo = future.get(); } catch (InterruptedException e) { //data accessible here } catch (ExecutionException e) { //data accessible here too } }Use a Map instead of a List to store your Futures and their corresponding Data, and use the Futures as keys into that map:
Map<Future<Foo>,Data> results = new HashMap<Future<Foo>,Data>(); for (Data data : dataList) { Callable<Foo> thread = new FooCallable(data); Future<Foo> result = this.executorService.submit(thread); results.put(result,data); } Iterator<Map.Entry<Future<Foo>,Data>> resultsIterator = results.entrySet().iterator(); while(resultsIterator.hasNext()) { Map.Entry<Future<Foo>,Data> entry = resultsIterator.next(); Future<Foo> future = entry.getKey(); Data data = entry.getValue(); Foo foo; try { foo = future.get(); } catch (InterruptedException e) { //data accessible here } catch (ExecutionException e) { //data accessible here too } }更多推荐
发布评论