简体   繁体   中英

usability of synchronized… methods in java.util.Collections

I'm looking at the static method

Collections.synchronizedList(List<T> list)

Javadoc says

It is imperative that the user manually synchronize on the returned list when iterating over it...

What's the purpose of creating a synchronized list if I still have to manually synchronize it?

The reason why you would use

Collections.synchronizedList(List<T> list)  

is because all the methods but the iterator are synchronized using the list itself as the mutex so you don't have to do

synchronized(list) {
    list.add(type);
}   

Instead you can just do

list.add(type);  

and it will be thread safe.

The only method which isn't synchronized is when iterating the list. The list iterator can't be return in a synchronized fashion, since you will be iterating through it afterwards which is why it is required to manually synchronize the list. So in conclusion, you only have to synchronize the list when iterating over it, everything else you don't have to.

The java collections tutorial explains this. Basically, each iteration reauires multiple calls to the underlying collection. These calls muct be atomicised as a single 'transaction'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM