Java – how does the behavior differ between these two synchronous usages in the list?

List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<String>();
list.add("a");
...
list.add("z");

synchronized(list) {
    Iterator<String> i = list.iterator();
    while(i.hasNext()) {
        ...
    }
}

and

List<String> list = new ArrayList<String>();
list.add("a");
...
list.add("z");

List<String> synchronizedList = Collections.synchronizedList(list);

synchronized(synchronizedList) {
    Iterator<String> i = synchronizedList.iterator();
    while(i.hasNext()) {
        ...
    }
}

Specifically, when synchronized lists provide thread safe access to lists, I don't know why synchronization is needed in the second instance

Solution

If you do not lock the iteration, if another thread modifies it during the loop, you will get a concurrentmodificationexception

Synchronizing all methods does not prevent this from happening

This (and many other things) is collections The reason why synchronized * is completely useless You should use Java util. Class in concurrent You should think carefully about how to ensure your safety

The general rule of thumb is:

For more information, see my blog

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>