开发者

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'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜