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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With