Re: ArrayList - Reading and writing
On 2008-07-20 00:48 +0100, Daniel Pitts allegedly wrote:
Daniele Futtorovic wrote:
On 2008-07-15 16:07 +0100, Jimmie Tyrrell allegedly wrote:
That was perfect. I had tried using synchronized before - wasn't
aware that _both_ operations needed to be synchronized. It seems
overtly logical now :)
Thanks for the help!
The problem with shakah's approach is that it monopolises the List
Object during the whole process of Iteration -- which may go down well,
but which may also pose some problems.
It would be better to iterate over a copy. You'd still synchronise the
process of copying, as well as the process of adding.
For instance (non-generic code for the sake of simplicity):
List myQueue = ...;
/* adding */
synchronized( someLock ){
myQueue.add(newObject);
}
/* end adding */
/* iterating */
List copy;
synchronized( someLock ){
copy = java.util.Collections.unmodifiableList(myQueue);
}
for(Iterator it = copy.iterator(); it.hasNext();){
//do something involving it.next();
}
/* end iterating */
Note that copying the List doesn't involve copying its /content/.
And what you did doesn't copy the list either, it just wraps it. To copy
it you'd actually have to use new ArrayList(someQueue);
Yes, I'd corrected that in a sucessive post.
The thing is,
that this process ALSO iterates over the whole list (although only for a
fast reference copy).
I had just made a suggestion that is another way to solve the OPs
problem, using new Java 1.5 Concurrency API features.
The approach to take depends on the size of the list, and the required
performance characteristics of the UDP handler.
Now that you mention it -- yeah, his scenario really calls for a
blocking queue. Although I had even named a variable in the sample code
I posted thus, I had focussed my attention too strongly on the iteration
part.
Thanks for improving the answers.
--
I would like to thank all the fish who have taken part in this post.
I hope that other fish will follow the example of those who have
participated, so that, in future, fish all over the world will live
together in harmony and understanding, and put aside their petty
differences, cease pursuing and eating each other and live for a
brighter, better future for all fish, and those who love them.