从期货中获取值时,为什么会收到NullPointerException? [英] Why am I getting a NullPointerException when fetching values from Futures?

查看:114
本文介绍了从期货中获取值时,为什么会收到NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ExecutorServiceExecutorService同时运行某些Callables.这是我的代码的简化版本:

I'm using and ExecutorService to concurrently run some 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();

我在这段代码if (futFuture.get().isEmpty() == false)上得到一个NullPointerException.我似乎无法弄清楚为什么或为什么这段代码可能为空.

I get a NullPointerException on this bit of code if (futFuture.get().isEmpty() == false). I can't seem to figure out why or how this bit of code can possibly be null.

如果您查看我的Callable,您会发现我正在捕获所有异常并仅打印stacktrace,而我总是返回new ArrayList<Book>().

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>().

我并没有帮助其他人在SO上调试我的代码汤,但是有时候每个人都遇到了障碍,但是这种异常教会了我一件事-将方法链接在一起时,总是很难调试.

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.

推荐答案

可能是objAmazon.doSearch(strQuery)返回null吗? 为此,将支票插入Callable.

May be objAmazon.doSearch(strQuery) returns null? Insert a check for this into the Callable.

如果计算以异常终止(因此不必捕获Callable中的所有异常),Future本身绝不能为null,并且Future.get()不会返回null.

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).

这篇关于从期货中获取值时,为什么会收到NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆