了解Java的同步集合

了解Java的同步集合

本文介绍了了解Java的同步集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关以下内容的Java官方包装器实现,它们是 Collections 中的静态方法,用于获取同步的集合,例如: List< Type> list = Collections.synchronizedList(new ArrayList< Type>());
...

我不明白的是以下内容(我引用java doc):

I'm reading the java official doc regarding wrappers implementation, which are static methods in Collections used to get synchronized collection, for example : List<Type> list = Collections.synchronizedList(new ArrayList<Type>());...
the thing that I did not understand is the following (I quote from the java doc ) :

如何迭代时可能每一个线程安全都需要手动同步

how it could be every bit as thread-safe an need to manually synchronize when iterating ??

推荐答案

从某种意义上讲,线程安全是线程安全的,但是如果您对线程执行复合操作,收集,那么您的代码就有并发问题的风险。

It is thread safe in the sense that each of it's individual methods are thread safe, but if you perform compound actions on the collection, then your code is at risk of concurrency issues.

ex:

List<String> synchronizedList = Collections.synchronizedList(someList);
synchronizedList.add(whatever); // this is thread safe

单个方法 add()是线程安全的,但是如果我执行以下操作:

the individual method add() is thread safe but if i perform the following:

List<String> synchronizedList = Collections.synchronizedList(someList);
if(!synchronizedList.contains(whatever))
       synchronizedList.add(whatever); // this is not thread safe

if-then-add操作不是线程安全的,因为其他一些操作线程可能在 contains()检查之后将任何内容添加到列表中。

the if-then-add operation is not thread safe because some other thread might have added whatever to the list after contains() check.

这篇关于了解Java的同步集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:21