What is the point of thread-safety Collections.synchronizedList if it still needs to be synchronized during iteration. Here CopyOnWriteArrayList does not need to be synchronized + it never throws a ConcurrentModificationException. If possible, an example where Collections.synchronizedList makes sense to use instead of the usual ArrayList.
1 answer
Collections.synchronizedList in comparison with ArrayList has synchronized add, remove, etc. operations. But the iterator in this case is not synchronized. Therefore, when using an iterator, synchronizedList must be synchronized manually.
List list = Collections.synchronizedList(new ArrayList()); ... synchronized(list) { Iterator i = list.iterator(); // Синхронизированный итератор while (i.hasNext()) foo(i.next()); } CopyOnWriteArrayList is really fully synchronized, including for the iterator. What exactly to use depends on the application logic and personal preferences.
|