is Java HashSet thread-safe for read only?

前端 未结 7 1411
清酒与你
清酒与你 2021-02-01 16:51

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

7条回答
  •  梦毁少年i
    2021-02-01 16:58

    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().

提交回复
热议问题