Concurrency - Is the behaviour due to compiler optimization or ?
It may not be a right group to post this query, but my problem do have some relation to the subject.
Here is the code
import java.util.*;
publicclass TestConcurrentRemove{
static List lst =new ArrayList();/* Yes it is ArrayList */
publicstaticvoid main( String[] args ){
/* Populating the list with some unique strings 0:0, 0:1, ... 1:0, 1:1, ... 999:999*/
for(long i = 0; i < 1000; i++ ){
for(long j = 0; j < 1000; j++ ){
lst.add( i +":" + j );
}
}
/*Creating threads which has a reference to the list, also naming them*/
Thread em1 =new ItemRemover( lst );
em1.setName("[Thread-1]" );
Thread em2 =new ItemRemover( lst );
em2.setName("[Thread-2]" );
/*Start the threads */
em1.start();
em2.start();
}
staticclass ItemRemoverextends Thread{
List lol_;
public ItemRemover( List lol ){
lol_ = lol;
}
publicvoid run(){
/* Remove the top most element from the list and print them. */
while( lol_.size() > 0 ){
System.out.println( getName() +" removed " + lol_.remove(0) );
}
}
}
}
Agreed ArrayList implementation is not synchronized.
But the question is what causes an O/P like this
[Thread-2] removed 5:945
[Thread-1] removed 5:946
[Thread-1] removed 5:946
[Thread-2] removed 5:946
..
[Thread-1] removed 5:977
[Thread-2] removed 5:977
[Thread-1] removed 5:977
...
[Thread-1] removed 20:460
[Thread-2] removed 20:460
[Thread-1] removed 20:460
[Thread-2] removed 20:460
[Thread-1] removed 20:460
[Thread-2] removed 20:460
As we can see the same thread removes the same element again.
Thanks in advance for your answers.

