Thread Java 30 days- day 6(CopyOnWriteArrayList)

paul chou
2 min readAug 5, 2023

--

When we need to read the contents of a List while another Thread needs to add items to the same List, using the ArrayList approach can lead to issues. The problem arises due to the lack of thread safety in ArrayList. It means that multiple threads simultaneously reading and modifying the ArrayList can cause race conditions and lead to unpredictable results or errors during program execution. The sample code is as follows:


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Semaphore;


public class Main {


public static void main(String[] args) throws Exception {

List<String> list = new ArrayList<String>();
for(int i = 0; i < 100; i ++){
list.add("a" + i);
}

Thread thread = new Thread(new ThreadExample(list));
thread.start();


for(String s: list) {
System.out.println(s);
}




}


public static class ThreadExample implements Runnable{
private List<String> list;

public ThreadExample(List<String> list) {
this.list = list;
}

@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
list.add("b" + i);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}



}

The main program starts threads to read and write data simultaneously. This concurrent access may lead to exceptions during the execution of this program, as follows:

The main reason for the occurrence of the Exception is that ArrayList cannot handle simultaneous read and write operations, which may lead to errors.

To resolve this issue, one can use the synchronized approach introduced earlier, but it may result in slower execution since it restricts reading while writing or writing while reading. Consequently, this method affects the performance negatively. As an alternative, CopyOnWriteArrayList can be used, which creates a copy of the list’s content during read operations. This way, it avoids the problems encountered when attempting simultaneous read and write operations on a List.


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Semaphore;


public class Main {


public static void main(String[] args) throws Exception {

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

for(int i = 0; i < 100; i ++){
list.add("a" + i);
}

Thread thread = new Thread(new ThreadExample(list));
thread.start();


for(String s: list) {
System.out.println(s);
}




}


public static class ThreadExample implements Runnable{
private List<String> list;

public ThreadExample(List<String> list) {
this.list = list;
}

@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
list.add("b" + i);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}

}

--

--