If I have an instance of an HashSet after I ran it through Collections.unmodifiableSet(), is it thread-safe?
I\'m asking this since Set documentation states that it\'s n
It would be thread safe, but only owing to the fact that Collections.unmodifiableSet()
internally publishes the target Set
in safe manner (via the final
field).
Note that in general statements such as "read-only objects are always thread-safe" are not correct, since they don't take into account possibility of operation reordering.
It's (theoretically) possible that, due to operation reordering, a reference to that read-only object will become visible to other threads before object is completely initialized and populated with data. To eliminate this possibility you need to publish references to the object in safe manner, for example, by storing them in final
fields, as it's done by Collections.unmodifiableSet()
.