Collections.synchronizedList and synchronized

前端 未结 6 1971
星月不相逢
星月不相逢 2020-11-27 11:36
List list = Collections.synchronizedList(new ArrayList());
synchronized (list) {
    list.add(\"message\");
}

Is the bl

6条回答
  •  清歌不尽
    2020-11-27 12:19

    You don't need to synchronize as you put in your example. HOWEVER, very important, you need to synchronize around the list when you iterate it (as noted in the Javadoc):

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

    List list = Collections.synchronizedList(new ArrayList());
    ...
    synchronized(list) {
        Iterator i = list.iterator(); // Must be in synchronized block
        while (i.hasNext())
            foo(i.next());   
    }
    

提交回复
热议问题