I am trying to add String
values to an ArrayList
using two threads. What I want is that while one thread is adding the values the other thread should not interfere so I have used the Collections.synchronizedList
method. But it appears that if I don't explicitly synchronize on an object the adding is done in an unsynchronized way.
Without explicit synchronized block:
public class SynTest {
public static void main(String []args){
final List<String> list=new ArrayList<String>();
final List<String> synList=Collections.synchronizedList(list);
final Object o=new Object();
Thread tOne=new Thread(new Runnable(){
@Override
public void run() {
//synchronized(o){
for(int i=0;i<100;i++){
System.out.println(synList.add("add one"+i)+ " one");
}
//}
}
});
Thread tTwo=new Thread(new Runnable(){
@Override
public void run() {
//synchronized(o){
for(int i=0;i<100;i++){
System.out.println(synList.add("add two"+i)+" two");
}
//}
}
});
tOne.start();
tTwo.start();
}
}
The output that I got is:
true one
true two
true one
true two
true one
true two
true two
true one
true one
true one...
With the explicit synchronized block uncommented I'm stopping the interference from the other thread while adding. Once the thread has acquired the lock it is executing until it is finished.
sample output after uncommenting the synchronized block:
true one
true one
true one
true one
true one
true one
true one
true one...
So why is the Collections.synchronizedList()
not doing the synchronization?
one two one two one two...
? The synchronization is on the list operation, not on the threads – Royal