0

Here below is a code snippet in java.

Collection contextPages = (Collection) getContextPages();
Iterator contextPageIter = contextPages.iterator();
while (contextPageIter.hasNext()) {
    Page contextPage = (Page) contextPageIter.next();
    String result = contextPage.getResult();        // <-- Null pointer exception here
    // Other stuff which this API does.
}

This code has been in production for a while. But for some reason, we hit a null pointer at String result = contextPage.getResult();.

So looks like even though we did a check for hasNext(), the next() method is returning null.

One possibility is that the collection itself has a null, but is it possible that this code could yield to a null pointer in a multi-threaded environment?

2
  • Normally, it is not allowed to modify a collection concurrently. However, there is no guarantee that this will be detected by the collection (though it will try to do so). It would help to know the exact class of contextPages. Commented Sep 30, 2014 at 18:44
  • Anything could happen if the collection is not thread-safe, and one thread modifies the collection while another thread is using an Iterator for the collection. Do you have some reason to suspect that another thread may be using the collection at the same time? Commented Sep 30, 2014 at 19:07

2 Answers 2

2

Some collections allow you to add a null, so iter.next will return it and when you use it -> NPE

To demonstrate

@Test
public void testNull() {
    Collection<Object> c = new ArrayList<>();
    c.add(null);
    Iterator<Object> iterator = c.iterator();
    Assert.assertTrue(iterator.hasNext());
    Object o = iterator.next();
    Assert.assertNull(o);
}

So check that you don't add null references to the collection or check for null before using the result of Iterator#next()

Page contextPage = (Page) contextPageIter.next();
String result = null;
if(contextPage != null) {
        result = contextPage.getResult();
}

There should be no difference between single- and multi- threaded applications, just make sure you don't add null.

Sign up to request clarification or add additional context in comments.

Comments

0

Better to check for null before using the result of Iterator.next()

Try this -

Page contextPage = (Page) contextPageIter.next();
String result = null;
if(contextPage != null) {
        result = contextPage.getResult();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.