Search code examples
javaiteratorjava.util.concurrentsynchronizedcollection

Why do we use synchronized collection if it doesn't guarantee the synchronized access on iterators?


For example, in the code below, we have to wrap list in a synchronized block when doing the iteration. Does the Collections.synchronizedList make the list synchronized? Why do we do this if it doesn't provide any convenience? Thanks!

List<Integer> list = Collections.synchronizedList( new ArrayList<>(Arrays.asList(4,3,52)));

synchronized(list) { 
      for(int data: list)
         System.out.print(data+" "); 
}

Solution

  • See https://docs.oracle.com/javase/tutorial/collections/implementations/wrapper.html

    The reason is that iteration is accomplished via multiple calls into the collection, which must be composed into a single atomic operation.

    Also see https://www.baeldung.com/java-synchronized-collections