0

will the Guava Multimap .values() collection throw concurrent modification exceptions if the return collection if iterated on another thread while the main multimap is changed on another thread?

If so how can this is avoided?

Basically I need to return the Multimap .values() collection from a method running on another thread while the main thread may update the Multimap.

Does this statement from the docs mean I'll be ok? " *

This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedListMultimap}."

Thanks

CodingHero
  • 2,865
  • 6
  • 29
  • 42
  • Yes it will. See [this SO answer][1] for more details. [1]: http://stackoverflow.com/questions/1572178/guava-multimap-and-concurrentmodificationexception – Brian Agnew May 23 '14 at 10:44

1 Answers1

0

Short answer: yes it does throw ConcurrentModificationException; I was able to get one using:

 Multimaps.synchronizedListMultimap(ArrayListMultimap.<Integer, Integer>create());

The iterator that is return for Multimap.values() is a proxy(composite iterator) for HashMap and ArrayList

As a quick hacky ugly fix you can just shyncronize on that multimap. This works because Multimaps.synchronizedListMultimap returns a SynchronizedListMultimap. SynchronizedListMultimap extends SynchronizedObject and this one is build with a null mutex so it will use itself for syncronization.

Liviu Stirb
  • 5,876
  • 3
  • 35
  • 40
  • Of course that if you change that multimap from the same thread while iterating even if you are synchronized it will still throw exception. – Liviu Stirb May 23 '14 at 12:16