Background
I would like to understand why a snippet of code does not throw a NullPointerException.
Source Code
Consider the following code:
public class Agent {
public List files = new ArrayList();
public void deliver() {
if( files != null && files.iterator().hasNext() ) {
File file = (File)files.iterator().next();
}
files = new ArrayList();
}
}
The deliver method is called repeatedly, whilst the following code runs in a separate thread:
public void run() {
agent.files = null;
}
There is only a single agent instance.
Problem
A NullPointerException is never thrown.
However, when the deliver method pauses, even for 0 milliseconds, a NullPointerException is thrown as expected:
public void deliver() {
if( files != null ) {
Thread.currentThread().sleep( 0 );
if( files.iterator().hasNext() ) {
File file = (File)files.iterator().next();
}
}
files = new ArrayList();
}
My understanding was that there is, in theory, a race condition between checking for files == null and calling files.iterator().hasNext(). In practice, I cannot trigger the race condition without introducing the pause (i.e., splitting the null check from the subsequent method call).
Question
Why does the first deliver method not throw an exception when the null check and usage are combined in the same statement?
javapoutput where appropriate surrounding race condition areas? - nanofaradfilesvolatile? - OldCurmudgeon