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.

[3341 byte] By [ragsrinia] at [2007-11-26 23:05:53]
# 1

As we can see the same thread removes the same

element again.

It is because the internal data elements of ArrayList are being concurrently updated and therefore corrupted.

Anytime you concurrent update an Object that isn't thread safe you can have any number of unpredictable results. You can even have worse consequences than what you see here.

For example. Concurrently updating a HashMap can lead to an infinite loop.

In the case of ArrayList.remove(). Internally it uses

System.arraycopy(elementData, index+1, elementData, index,numMoved);

And one thread just recopies the same data again. Overwriting what the previous thread removed.

Take a look at [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html]ConcurrentLinkedQueue[/url]. Just don't use the size() method. Use isEmpty(), or just check if poll() returns null.

Caffeine0001a at 2007-7-10 13:59:07 > top of Java-index,Core,Core APIs...
# 2
Thanks for the answer and your time. After posting, later i realized this question is childish.For sure the subject of this thread is not related to the topic.
ragsrinia at 2007-7-10 13:59:07 > top of Java-index,Core,Core APIs...