Java 17 Recipes


-4. Iterating Through a Changing Collection


Download 3.2 Mb.
Pdf ko'rish
bet186/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   182   183   184   185   186   187   188   189   ...   245
Bog'liq
Java 17 Recipes

10-4. Iterating Through a Changing Collection
 Problem
You need to iterate over each element in a collection. However, other threads are 
constantly updating the collection.
 Solution 1
By using CopyOnWriteArrayList, you can safely iterate through the 
collection without worrying about concurrency. In the following solution, the 
startUpdatingThread() method creates a new thread, which actively changes the list 
passed to it. While startUpdatingThread() modifies the list, it is concurrently iterated 
using the stream forEach() function.
public class Recipe10_4 {
public static void main(String[] args) {
Recipe10_4 recipe = new Recipe10_4();
recipe.start();
}
private void start() {
System.out.println("Using CopyOnWrite");
copyOnWriteSolution();
}
Chapter 10 ConCurrenCy


360
private void stopUpdatingThread() {
updatingThread.interrupt();
}
Random random = new Random();
Thread updatingThread ;
private void startUpdatingThread(final List list) {
updatingThread = new Thread(() -> {
long counter =0;
while (!Thread.interrupted()) {
int size = list.size();
if (random.nextBoolean()) {
if (size > 1) {
list.remove(random.nextInt(size - 1));
}
} else {
if (size < 20) {
list.add("Random string "+counter);
}
}
counter ++;
}
});
updatingThread.start();
// let it warm up for a second
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void copyOnWriteSolution() {
CopyOnWriteArrayList list = new CopyOnWriteArrayList();
startUpdatingThread(list);
list.stream().forEach((element) -> {
Chapter 10 ConCurrenCy


361
System.out.println("Element :" + element);
});
stopUpdatingThread();
}
}
 Solution 2
Using a synchronizedList() method allows you to atomically change the collection. It 
also provides a way to synchronize safely on the list while iterating through it (which is 
done in the stream). The following is an example.
public class Recipe10_4 {
public static void main(String[] args) {
Recipe10_4 recipe = new Recipe10_4();
recipe.start();
}
private void start() {
System.out.println("Using SynchronizedList");

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   182   183   184   185   186   187   188   189   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling