Question

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;
    }
Was it helpful?

Solution

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;

OTHER TIPS

You need to make it synchronized to make it thread safe. Then you need use the Iterator to avoid ConcurrentModificationException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top