is Java HashSet thread-safe for read only?

前端 未结 7 1586
清酒与你
清酒与你 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:01

    HashSet will be threadsafe if used in a read-only manner. That doesn't mean that any Set that you pass to Collections.unmodifiableSet() will be threadsafe.

    Imagine this naive implementation of contains that caches the last value checked:

    Object lastKey;
    boolean lastContains;
    
    public boolean contains(Object key) {
       if ( key == lastKey ) {
          return lastContains;
       } else {
          lastKey = key;
          lastContains = doContains(key);
          return lastContains;
       }
    }
    

    Clearly this wouldn't be threadsafe.

提交回复
热议问题