简体   繁体   English

为什么从 Futures 获取值时会收到 NullPointerException?

[英]Why am I getting a NullPointerException when fetching values from Futures?

I'm using and ExecutorService to concurrently run some Callables .我正在使用和ExecutorService同时运行一些Callables Here's a simplified version of my code:这是我的代码的简化版本:

ArrayList<Book> objResults = new ArrayList<Book>();
ExecutorService esrExecutor = Executors.newFixedThreadPool(2);
Set<Callable<ArrayList<Book>>> setCallables = new HashSet<Callable<ArrayList<Book>>>();

setCallables.add(new Callable<ArrayList<Book>>() {

    public ArrayList<Book> call() throws Exception {    
        ArrayList<Book> objAmazonResults = new ArrayList<Book>();

        try {    
            Amazon objAmazon = new Amazon();
            objAmazonResults = objAmazon.doSearch(strQuery);    
        } catch (Exception e) {
            e.printStackTrace();
        }    
        return objAmazonResults;    
    }

});


List<Future<ArrayList<Book>>> lstFutures;
try {
    lstFutures = esrExecutor.invokeAll(setCallables);

    for(Future<ArrayList<Book>> futFuture : lstFutures){
        if (futFuture.get().isEmpty() == false) //NullPointerException occurs here
            objResults.addAll(futFuture.get());
    }
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

esrExecutor.shutdown();

I get a NullPointerException on this bit of code if (futFuture.get().isEmpty() == false) . if (futFuture.get().isEmpty() == false)我在这段代码上得到NullPointerException I can't seem to figure out why or how this bit of code can possibly be null.我似乎无法弄清楚为什么或如何这段代码可能为空。

If you look at my Callable you'll see that I'm trapping all exceptions and simply printing the stacktrace and I always return new ArrayList<Book>() .如果您查看我的Callable您会发现我正在捕获所有异常并简单地打印堆栈跟踪,并且我总是返回new ArrayList<Book>()

I'm not much for helping other debug my code soup on SO but sometimes everyone hits a roadblock but this kind of exceptions has taught me one thing — when chaining methods together, it's always harder to debug.我不太会帮助其他人在 SO 上调试我的代码汤,但有时每个人都会遇到障碍,但这种异常教会了我一件事——将方法链接在一起时,调试总是更困难。

May be objAmazon.doSearch(strQuery) returns null?可能是objAmazon.doSearch(strQuery)返回 null? Insert a check for this into the Callable .Callable插入一个检查。

The Future itself should never be null, and Future.get() will not return null, if the computation terminated with an exception (so catching all exceptions inside the Callable is not necessary). Future本身永远不应该为 null,并且Future.get()不会返回 null,如果计算因异常而终止(因此不需要在Callable捕获所有异常)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM