Firstly I'm not using iterator here.
I'm using 2 threads on an shared ArrayList ,1st is used to adding values into ArrayList and other is to make a temporary copy of it and do some operations on it and then removing all temp elements from original list.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArraylistTest {
public static void main(String...ar){
new AddingThread().start();
new RemovalThread().start();
}
}
class RemovalThread extends Thread{
static List<Integer> originalBigList = new ArrayList<>();
@Override
public void run(){
System.out.println("RemovalThread started");
while(true){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("creating copy of originalBigList");
List<Integer> tempList = new ArrayList<>(originalBigList);
System.out.println("copied list");
//
//some operations on copied temp list
//
System.out.println("removing tempList elements after completing operations");
System.out.println("originalBigList before removing size "+originalBigList.size());
originalBigList.removeAll(tempList);
System.out.println("removed!!");
System.out.println("after size "+originalBigList.size());
}
}
}
class AddingThread extends Thread{
@Override
public void run(){
System.out.println("Adding thread started");
int ctr = 0;
while(true){
RemovalThread.originalBigList.add(ctr);
ctr++;
}
}
}
Output :-
Adding thread started
RemovalThread started
creating copy of originalBigList
copied list
removing tempList elements after completing operations
originalBigList before removing size 4102267
Exception in thread "Thread-0" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at AddingThread.run(ArraylistTest.java:47)
Now my question is that i'm seeing in the output that the statement which is copying the list is executed which is making temp list from original list, but removal statement is not executing and not giving any Exception and i'm using simple arraylist not synchronised,so why is it so?
Is there any internal lock on remove or add operation? if yes then what is the use of Collections.synchronised( arraylist )?