Why is Arraylist's size not right when multiple threads add elements into it?
threadCount = 100;
List<Object> list = new ArrayList<>();
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new MyThread(list, countDownLatch));
thread.start();
}
class MyThread implements Runnable {
// ......
@Override
public void run() {
for (int i = 0; i < 100; i++) {
list.add(new Object());
}
}
}
When this program is done, the size of the list should be 10000. Actually, the size may be 9950, 9965 or some other numbers. Why?
I know that why this program may raise IndexOutofBoundsException
and why there are some nulls in it, but I just do not understand why the size is wrong.