CopyOnWriteArrayList vs ArrayList
I am studying the java.util.concurrent package. I reread a bunch of articles, but I can't understand the principle of thread safety of CopyOnWriteArrayList. More precisely, the principle realized that a duplicate of the collection is being created, and work is happening with it. But in practice, I can not implement it. I didn't find a decent example. Here in this article in the example, it is only clear that when using CopyOnWriteArrayList when iterating through the iterator, you can not delete the element. The most important question. In which cases In some cases, we can use the thread-safe CopyOnWriteArrayList instead of synchronization. I would appreciate any example.
1 answers
ArrayList in conjunction with synchronization in some high-load application will run slower than CopyOnWriteArrayList, since the normal ArrayList will be blocked by some thread entirely and will be inaccessible to other threads. At the same time, CopyOnWriteArrayList does not require thread locks, since each thread will work with its own copy of the sheet. When using CopyOnWriteArrayList, you can delete an element when iterating through it. But this will not affect that if you are going to make an output to the screen and delete an item, you will get an output to the screen of the original list in its entirety. Here here is a fairly clear example of how CopyOnWriteArrayList works.
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListExample
{
List<String> list;
public CopyOnWriteArrayListExample()
{
List<String> lst = new ArrayList<String>();
lst.add("Java");
lst.add("J2EE");
lst.add("J2SE");
lst.add("Collection");
lst.add("Concurrent");
list = new CopyOnWriteArrayList<String>(lst);
System.out.println("ЦИКЛ с изменением");
printCollection(true);
System.out.println("\nЦИКЛ без изменением");
printCollection(false);
}
private void printCollection(boolean change)
{
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String element = iterator.next();
System.out.printf(" %s %n", element);
if (change) {
if (element.equals("Collection")) {
list.add("Новая строка");
list.remove(element);
}
}
}
}
public static void main(String args[])
{
new CopyOnWriteArrayListExample();
System.exit(0);
}
}
At the output, you will get the following result:
ЦИКЛ с изменением
Java
J2EE
J2SE
Collection
Concurrent
ЦИКЛ без изменением
Java
J2EE
J2SE
Concurrent
Новая строка