Reputation: 16671
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;
}
Upvotes: 3
Views: 115
Reputation: 41117
You need to make it synchronized
to make it thread
safe. Then you need use the Iterator
to avoid ConcurrentModificationException
.
Upvotes: -1
Reputation: 121830
It will throw a ConcurrentModificationException
for each invalid UUID.
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. You have to create an iterator and use .remove()
.
For instance:
final Iterator<String> iterator = uuids.iterator();
String uuid;
while (iterator.hasNext()) {
uuid = iterator.next();
if (!checkIfValidUUID(uuid))
iterator.remove();
}
return uuids;
Upvotes: 3