threads
Safe collection iteration example
In this example we shall show you how to obtain a safe Collection iteration. We are using the List implementation of Collection, but the Collections API provides methods for such operations in other Collection implementations too, such as Map and Set. To obtain a safe Collection iteration one should perform the following steps:
- Call
synchronizedList(List list)
API method of Collections to get a synchronized (thread-safe) list. - Add elements to the list, using
add(Object e)
API method of List. - Set the list in a
synchronized
statement and then iterate through its elements, using theiterator()
API method of the List andhasNext()
,next()
API methods of Iterator,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class SafeCollectionIteration extends Object { public static void main(String[] args) { List words = Collections.synchronizedList(new ArrayList()); words.add("JavaCodeGeeks"); words.add("is"); words.add("very"); words.add("cool!"); synchronized (words) { Iterator it = words.iterator(); while (it.hasNext()) { String str = (String) it.next(); System.out.println("" + str + ", characters="+ str.length()); } } } }
Output:
JavaCodeGeeks, characters=13
is, characters=2
very, characters=4
cool!, characters=5
This was an example of how to obtain a safe Collection iteration in Java.