Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 892
Chin Avatar asked Dec 05 '25 19:12

Chin


2 Answers

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.

like image 57
yshavit Avatar answered Dec 08 '25 12:12

yshavit


HashSet isn't thread safe. ImmutableSet.copyOf needs to iterate over your HashSet, which isn't safe if another thread is concurrently modifying it. What's more, your having two threads modifying the HashSet is already unsafe.

like image 28
ColinD Avatar answered Dec 08 '25 13:12

ColinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!