[英]is the following method thread safe
I want to know if the following method will be thread safe. 我想知道以下方法是否是线程安全的。
use cases : I pass two collection from different locations... 用例:我从不同的位置传递两个集合...
public static Collection<String> checkIfValidUUIDCollectionAndRefine(Collection<String> uuids){
for(String uuid : uuids){
if(!checkIfValidUUID(uuid)){
uuids.remove(uuid);
}
}
return uuids;
}
It will throw a ConcurrentModificationException
for each invalid UUID. 它将为每个无效的UUID抛出
ConcurrentModificationException
。
Second point is because of this: 第二点是因为:
for(String uuid : uuids){
if(!checkIfValidUUID(uuid)){
uuids.remove(uuid);
}
}
The foreach loop creates an iterator internally, but you modifiy this iterator. foreach循环在内部创建一个迭代器,但是你修改了这个迭代器。 You have to create an iterator and use
.remove()
. 您必须创建一个迭代器并使用
.remove()
。
For instance: 例如:
final Iterator<String> iterator = uuids.iterator();
String uuid;
while (iterator.hasNext()) {
uuid = iterator.next();
if (!checkIfValidUUID(uuid))
iterator.remove();
}
return uuids;
You need to make it synchronized
to make it thread
safe. 您需要使其
synchronized
以使其thread
安全。 Then you need use the Iterator
to avoid ConcurrentModificationException
. 然后,您需要使用
Iterator
来避免ConcurrentModificationException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.