This is just a quick word of advice to anyone out there writing threaded code with collections. I recently had to fix an old neglected web application that was having some serious threading issues and came across this little gem.
Creating a synchronized collection is as easy. All you need to do is...
List<Long> myList = Collections.synchronizedList(new ArrayList<Long>());
However, be careful when iterating over the collection. You still need to manually synchronize code that iterates over it, even though the collection itself is synchronized. Standard operations like adding or removing elements from the collection are thread-safe and will behave as expected in a multi-threaded environment. But iterating is not as simple.
If you want to iterate over a collection that will potentially be accessed by other threads simultaneously, always synchronize on the list itself. ie:
List<Long> myList = Collections.synchronizedList(new ArrayList<Long>());
// thread safe code
synchronized(myList) {
for (Long l : myList) {
// do something with l here
}
}
Failure to synchronize on the collection can cause all kinds of unexpected behavior. Typically you'll get a ConcurrentModificationException if the collection is modified while you're iterating over it, but there are no guarantees. And that's the problem. An application that falls over and dies is bad, but at least you know it's broken. An application that continues on merrily despite being broken is a very bad thing!