cuncurrency issue using ArrayList

Hi all

I have an arrayList object, 10 threads are populating data in to that arrayList object, another main thread will fetch data from that object. I am using iterator object to run the while loop with hasNext() method to fetch data in that main thread. but if that main thread runs before the other 10 threads then this loop fails because that arrayList object will not contain any element.

Previously i used java.util.concurrent.LinkedBlockingQueue where this class contains take() which waits untill there is an element in the queue and fetches it but i changed to arrayList because of queue size problem.

please help me in constructing a loop which doesnt fail like above.

Thanks

[716 byte] By [mullapudia] at [2007-11-27 10:00:07]
# 1
Have you tried CopyOnWriteArrayList?The iterator() method is unsafe with concurrent accesses to ArrayList!
alanmpa at 2007-7-13 0:31:17 > top of Java-index,Core,Core APIs...
# 2
Hi thanks for the reply. i dont know about that.. can u please elaborate ur explanationthanks
mullapudia at 2007-7-13 0:31:17 > top of Java-index,Core,Core APIs...
# 3

From http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html

"The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException"

Your problem seems to be composed of two seperate problems, 1) how to synchronise the arraylist and 2) How to signal to threads there is data to take out

I would seriously advise against using iterators in this case, they are NOT designed for this at all!

A better idea would be something along the lines:

while(continueRunning)

{

synchronized(_arrayList)

{

if (_arrayList.size() > 0)

{

Object o = _arrayList.get(0);

// Do something with object

}

}

}

[code]

}

[/code]

And on the other side:

synchronized(_arrayList)

{

_arrayList.put(object);

_arrayList.notifyAll();

}

alanmpa at 2007-7-13 0:31:17 > top of Java-index,Core,Core APIs...
# 4

> A better idea would be something along the lines:

>

> > while(continueRunning)

> {

>synchronized(_arrayList)

> {

>if (_arrayList.size() > 0)

> {

>Object o = _arrayList.get(0);

> // Do something with object

>}

I guess here should be:

else {

wait();

}

>

> }

>

>

> }

>

>

>

> And on the other side:

>

> > synchronized(_arrayList)

> {

>_arrayList.put(object);

> _arrayList.notifyAll();

> }

>

_Dima_a at 2007-7-13 0:31:17 > top of Java-index,Core,Core APIs...