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());
}
}

