Search code examples
javamultithreadingguava

Is guava ImmutableSet.copyOf() thread safe?


I would like to know if this call is thread safe. For example, if I have a set s:

Set<String> s = new HashSet<>();

and two threads A and B, thread A modifying the set:

for (int i = 0; i < 1234; i++) {
    // add, remove from s
}

while thread B creating ImmutableSets from s:

for (int i = 0; i < 5678; i++) {
    Set<String> newS =  ImmutableSet.copyOf(s);
}

Is it safe to assume that each time ImmutableSet.copyOf() is called I get an immutable set for a valid state of s in time? Will there be any kind of exception (like ConcurrentModificationException) that can occur?

If it is thread safe, how was it achieved without locking the set?


Solution

  • The relevant question isn't whether copyOf is safe -- it's whether the collection it's copying from is safe, and in particular, whether the Iterators that it creates via its iterator() method are thread-safe. For HashMap, that answer is no.