If the only thing changing between your working and non working code is the println statement, then you almost certainly have a threading issue. The System.out.println()
statement adds a small pause which may coincidentally cause it to behave, but is not solving the issue. You could do something like:
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
}
...in place of this and check for the same behaviour, if indeed it is the same then this pretty much confirms the threading issue. However, as pointed out below println()
also does a few other things such as causing a memory barrier, so this isn't a foolproof test. Another, perhaps better check could be to temporarily swap out ArrayList
for Vector
, which is thread safe - though this is a legacy collection so not recommended for use in the final code.
If this is the case, it sounds like you're not synchronising on ArrayList
calls properly - ArrayList
is not a thread safe collection. Whenever you read or write to the list, do it inside a synchronized block like so, synchronizing on the list:
synchronized(list) {
list.whatever();
}
...which will ensure that only one thread can access the ArrayList
at once, hopefully solving the threading issue.