1.

How To Avoid Concurrentmodificationexception While Iterating A Collection?

Answer»

You should first try to find another alternative iterator which are fail-safe. For example if you are using LIST and you can USE ListIterator. If it is legacy collection, you can use enumeration.

If above options are not possible then you can use one of three changes:

  • If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the RECOMMENDED APPROACH.
  • You can convert the list to an array and then iterate on the array.
  • You can lock the list while iterating by putting it in a synchronized block.

Please note that last two approaches will cause a performance hit.

You should first try to find another alternative iterator which are fail-safe. For example if you are using List and you can use ListIterator. If it is legacy collection, you can use enumeration.

If above options are not possible then you can use one of three changes:

Please note that last two approaches will cause a performance hit.



Discussion

No Comment Found