Learning something new everyday.
One of the best ways to avoid data manipulation problems in concurrent environments is to use read only data sets, one of the best way way to create a read only collection in Java is to use unmodifiableCollection method, however this method is not as innocent as you may think.
Behind the scenes unmodifiable collections are just a stub that redirect all methods to the original collections, except for methods that actually change the collection like add etc, in which case it throws an exception.
Test yourself, what happens when trying to iterate over an unmodifiable collection, when in a different thread new elements are added to the original collection… ConcurrentModificationException .
The best way to avoid it is to actually create a copy, e.g. new LinkedList(…)
To sum it up:
- Use unmodifiable collections whenever you want to make sure that in an external usage of the collection nothing will be modified, for example use it as a return value for your methods.
- Use different mechanisms in case of a multi-threaded environment, for example creating a real copy.