What are the possible problems caused by adding elements to unsynchronized ArrayList's object by multiple threads simultaneously?
Tried to run some experiments with a static ArrayList with multiple threads but couldn't find much.
Here i am expecting much of the side effects of not synchronizing an ArrayList or like Objects in a multithreaded environment.
Any good example showing side effects would be appreciable. thanks.
below is my little experiment which ran smoothly without any exception.
I also wonder why it didn't throw any ConcurrentModificationException
?
import java.util.ArrayList;
import java.util.List;
public class Experiment {
static List<Integer> list = new ArrayList<Integer>();
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("A " + i);
new Thread(new Worker(list, "" + i)).start();
}
}
}
class Worker implements Runnable {
List<Integer> al;
String name;
public Worker(List<Integer> list, String name) {
this.al = list;
this.name = name;
}
@Override
public void run() {
while (true) {
int no = (int) (Math.random() * 10);
System.out.println("[thread " + name + "]Adding:" + no + "to Object id:" + System.identityHashCode(al));
al.add(no);
}
}
}
ArrayList
does not enforce rules to disallow this. It'sIterator
does. If you wanna see results, try removing items from one of the threads while others are adding and see if the results are as expected. Right now, all threads are simply adding to the list (and print as soon as they add to it, which is the biggest flaw of this test), so you can't expect your console to display strange results – ChrissySystem.out.println
... – Chezstatic
in your example is the variable, not the list. But more to the point, what's important in your example is that the list is shared by several threads. You don't need astatic
variable to share data: That's just one easy way of doing it. – Convoy