Java 17 Recipes


synchronizedListSolution()


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

synchronizedListSolution();
}
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));
}
Chapter 10 ConCurrenCy


362
} 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 synchronizedListSolution() {
final List list = Collections.synchronizedList(new 
ArrayList());
startUpdatingThread(list);
synchronized (list) {
list.stream().forEach((element) -> {
System.out.println("Element :" + element);
});
}
stopUpdatingThread();
}
}
The following is the output.
Using CopyOnWrite
Element :Random string 731774
Using SynchronizedList
Element :Random string 1100164
Element :Random string 1100177
Element :Random string 1100180
Chapter 10 ConCurrenCy


363
 How It Works
Java comes with many concurrent collection options. Which collection to use depends 
on how the read operations compare with the write operations within the context 
of your application. If writing occurs far and in-between compared with reads, 
using a CopyOnWriteArrayList instance is most efficient because it doesn’t 
block (stop) other threads from reading the list and is thread-safe to iterate over (no 
ConcurrentModificationException is thrown when iterating through it). If there are the 
same number of writes and reads, the SynchronizedList method from the Collections 
class is the preferred choice. 
In solution 1, the CopyOnWriteArrayList is being updated while you traverse 
the list. Because the recipe uses the CopyOnWriteArrayList instance, there is no need to 
worry about thread safety when iterating through the collection (as done in this recipe 
by using the stream). It is good to note that CopyOnWriteArrayList offers a snapshot 
in time when iterating through it. If another thread modifies the list as you’re iterating 
through it, the modified list is likely not visible when iterating.
Note Locking properly depends on the type of collection being used. any 
collections returned as a result of using Collections.synchronized can 
be locked via the collection itself (synchronized (collectionInstance)). 
however, some more efficient (newer) concurrent collections such as the 
ConcurrentMap cannot be used in this fashion because their internal 
implementations don’t lock in the object itself.
Solution 2 creates a synchronized list, which is created by using the Collections 
helper class. The Collection.synchronizedList() method wraps a List object (it 
can be ArrayList, LinkedList, or another List implementation) into a list 
that synchronizes the access to the list operations. Each time you need to iterate over 
a list (either by using the stream, a for loop, or an iterator), you must be aware of the 
concurrency implications for that list’s iterator. CopyOnWriteArrayList is safe to iterate 
over (as specified in the JavaDoc). But, the iterator of the SynchronizedList method from 
the Collections class must be synchronized manually (also specified in the JavaDoc 
Collections.synchronizedList iterator). In the solution, the list can safely be iterated 
while inside the synchronized(list) block. When synchronizing on the list, no read/
updates/other iterations can occur until the synchronized(list) block is completed.
Chapter 10 ConCurrenCy


364

Download 3.2 Mb.

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




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