synchronizedList vs. synchronize(myList)

The API states that when a list is created using:

List<String> sList = Collections.synchronizedList(new ArrayList<String>());

that iterations over the list must be synchronized as well by using

synchronized(sList){

Iterator<String> i = sList.iterator();

while (i.hasNext()){

foo(i.next());

}

}

Does this mean that operations to add()

and remove()

are thread safe and automatically synchronized?

Is using a Collections based synchronized list the same as if I synchronized every call to my list? Such as:

private ArrayList<String> list =new ArrayList<String>();

...

void reverseAndAdd(String s){

synchronzied(list){

list.add(new StringBuilder(s).reverse().toString());

}

}

...

synchronized(list){

Iterator<String> i = list.iterator();

while (i.hasNext()){

foo(i.next());

}

}

[1599 byte] By [bensteina] at [2007-11-27 6:09:55]
# 1

No. The synchronizedList just synchronizes each call to a method of the underlying list, so add() and remove() are synchronized and hence thread-safe. But your second example displays the important difference very nicely. Within that synchronized block you are repeatedly accessing the list, via the Iterator, and blocking other accesses to the list. If you didn't do that, but just used a synchronized list implementation, then other threads would be able to access and potentially modify the list in between your Iterator's accesses to the list.

DrClapa at 2007-7-12 17:14:32 > top of Java-index,Core,Core APIs...