Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Synchronization and collections
|
Posted: Apr 2, 2002 1:15 AM
|
|
As long as all access to the list is through the synchronized list that was returned, it should be thread safe. Note that in addition to what you have, you need to put the code that is using the list in a synchronized block. It is pretty easy to write a little test of this "theory" by making a simple program with several threads that fool around with the plain list and then the synchronized version of it.
By the way, why do you not use an Iterator to iterate through the list? That for-loop stuff on the List's size() is so twentieth century! Here is how I would do your example:
List list = Collections.synchronizedList( someListOfStuff );
synchronized(list)
{
Iterator it = list.iterator();
while(it.hasNext())
{
MyObject mo = (MyObject)it.next();
// ...some incredibly fascinating processing...
}
}
|
|