is Java HashSet thread-safe for read only?

前端 未结 7 1410
清酒与你
清酒与你 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条回答
  •  野的像风
    2021-02-01 17:00

    Every data structure is thread-safe if you don't mutate it.

    Because you have to mutate a HashSet in order to initialize it, it is necessary to synchronize once between the thread which initialized the set and all reading threads. You have to do it only one time. For example when you pass the reference to the unmodifiable set to a new thread which never touched it before.

提交回复
热议问题