CopyOnWriteArrayList did a good job. I can read from multiple threads at same time, but I can update from 1 thread. The way it works is that write uses separate copy of array, update info and set it back to original array.
Question is: Since write operations use separate copy, how they can't do it parallely? Since they work in different arrays now, there won't be any interference. So whoever writes 1st, it sets those new updates to an original array. So why does Java allow only one write?
Am I missing something here why can only 1 thread write?
If two threads add an element to a CopyOnWriteArrayList at the same time, we expect both elements to be present in the list afterwards. Elements getting lost due to race conditions is not what the designers and users of CopyOnWriteArrayList want.
To expand: if you have two threads, and they do the following operations:
thread 1:
list.add("A");thread 2:
list.add("B");The expected end result is that
listcontains both A and B, even if not necessarily in that order.