I am using multiple threads via an ExecutorService to add objects to a list with several for-loops. As the normal ArrayList is not thread-safe, I am using a CopyOnWriteList. However, adding the elements as in the code example below does not give me a list of (n1+n2) elements, so somehow there is a concurrency problem.
Where is the error in my thinking? Is CopyOnWriteList the correct choice for a thread-safe list?
public class myThread{
List<SomeObject> list;
public myThread(List<someObject> list){
this.list = list;
}
public void run(){
SomeObject instance = new SomeObject();
list.add(instance);
}
}
public static void main(String[] args) {
CopyOnWriteArrayList<someObject> syncList = new CopyOnWriteList<someObject>();
ExecutorService executor = Executors.newFixedThreadPool(4);
for(int i=0; i< n1; i++){
executor.submit(new myThread(syncList))
}
for(int i=0; i< n2; i++){
executor.submit(new myThread(syncList))
}
}