ConcurrentModificationException when using unmodifiableCollection

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:

  1. 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.
  2. Use different mechanisms in case of a multi-threaded environment, for example creating a real copy.

Leave a comment

Filed under API, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s