如何在ListeningExecutorService中抛出异常?

问题描述 投票:0回答:1

我在项目中使用了guava的ListeningExecutorService,对异常处理感到困惑。

我使用了线程池,向它提交任务,并为listenableFuture设置超时,并为其添加回调。

 final ListeningExecutorService threadPool = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());



 Futures.addCallback(listenableFuture, new FutureCallback<**>() {

        @Override
        public void onSuccess(@Nullable ** data) {
            xxxxxxx;
        }

        public void onFailure(Throwable t) {
            xxxxxxxxxx;
            if (t instanceof CancellationException) {
                throw new QueryException("yyyy");
            } else {
                throw new QueryException("zzzzz");
            }
        }
    });

我无法在回调中捕获异常。所以我使用另一个ListenableFuture来获取异常

 ListenableFuture allFutures = Futures.allAsList(allFuturesList);
        try {
            allFutures.get();
        } catch (CancellationException ce) {
            throw new QueryException("");
        } catch (InterruptedException t) {
            throw new QueryException("");
        } catch (ExecutionException e) {
            Throwable t = e.getCause();
            if (t instanceof QueryException)
                throw (QueryException) t;
            else
                throw new QueryException();
        } catch (QueryException qe) {
            throw qe;
        } catch (Exception e) {
            throw new QueryException();
        } finally {
        }

但是当我回调抛出一个QueryException时,allFutures无法捕获它,allFutures只能捕获一个没有详细错误消息的CancellationException。

如何获取详细错误消息?

guava threadpoolexecutor
1个回答
1
投票

Futures.allAsList doesn't do what you expect it to do

来自Javadoc :(重点是来自我)

取消此未来将尝试取消所有组件期货,如果任何提供的期货失败或被取消,这个也是。

您应该做的是创建自己的聚合未来。您可以将代码基于Guava自己的内部机制。有关更多信息,请参阅the source code

无论如何,不​​要在你的FutureCallback::onFailure方法中抛出异常。

© www.soinside.com 2019 - 2024. All rights reserved.