Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
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).
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.