Java Reference
In-Depth Information
You need to iterate over each element in a collection. However, other threads are con-
stantly updating the collection.
Solution 1
By using CopyOnWriteArrayList , you can safely iterate through the collection
without worrying about concurrency. In the following solution, the startUpdat-
ingThread() method creates a new thread, which actively changes the list passed to
it. While startUpdatingThread() modifies the list, it is concurrently iterated us-
ing the stream forEach() function.
private void copyOnWriteSolution() {
CopyOnWriteArrayList<String> list = new
CopyOnWriteArrayList<String>();
startUpdatingThread(list);
list.stream().forEach((element) -> {
System.out.println("Element :" + element);
});
stopUpdatingThread();
}
Solution 2
Using a synchronizedList() allows us to atomically change the collection. Also,
a synchronizedList() provides a way to synchronize safely on the list while it-
erating through it (which is done in the stream ). For example:
private void synchronizedListSolution() {
final List<String> list
= Collections.synchronizedList(new ArrayList<String>());
startUpdatingThread(list);
synchronized (list) {
list.stream().forEach((element) -> {
System.out.println("Element :" + element);
});
}
Search WWH ::




Custom Search