0
private static class C {
    Set<String> myset;

    public Set<String> get() {
        return myset;
    }

    public void set() {
        myset = new HashSet<>();
    }
}

I have once C class instance and multiple threads calling get and set. Is this thread safe without synchronized block? I think it is since assignment is atomic.

codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167
  • What makes you think that this is thread safe? Variable `myset` is still global in class `C`! – user2004685 Feb 24 '18 at 00:28
  • No, not thread safe at all. The **reference** `myset` needs to be guarded, even if it refers to a thread safe class (`Collections.synchronizedSet()` https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedSet-java.util.Set- ), which in this case it does not. – markspace Feb 24 '18 at 00:57
  • From the duplicate: _As noted in the comments, atomicity does not imply visibility. So while another thread is guaranteed not to see a partially written int, it may never see the new value._ The same applies here. A thread is guaranteed to see a fully written `Set` reference value, but it might not see any new value. – Sotirios Delimanolis Feb 24 '18 at 00:59

0 Answers0