java - 出现异常时如何引用原始数据?

标签 java multithreading asynchronous

我正在使用 ExecutorService 运行一些可调用线程。在提交给 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
            //
        }
    }
}

最佳答案

使用映射而不是列表来存储您的Futures及其相应的数据,并使用Futures作为该映射的键:

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
    }
}

关于java - 出现异常时如何引用原始数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16743644/

相关文章:

javascript - 渲染组件后 API 调用返回图像

multithreading - Rust中的多线程备忘录

c# - Entity Framework 中的异步查询和延迟加载

java - Tomcat 5.5 : The requested resource is not available

java - 此代码的输出清晰

java - 在构建过程中集成系统测试

Python:使用多处理进行并行图像读取和预处理

java - 将 JLabel 类绘制到另一个 JPanel 类时出现问题

java - 停放 JAVA 线程会导致释放任何获取的监视器吗

c++ - 强制 C++ 程序在 Visual Studio 调试器中暂停