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

callable, executorservice, java, nullpointerexception

Solution

May be `objAmazon.doSearch(strQuery)` returns null? Insert a check for this into the `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).

Problem

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

Original source