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 list = new ArrayList();
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 al;
String name;
public Worker(List 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);
}
}
}
No comments:
Post a Comment