0

I've seen a class do something like this

class Foo {
private final Set<Bar> set = Collections.synchronizedSet(new HashSet<>));

     public void add(Bar b) {
          set.add(b);
     }   

}

However, the final set is not initialized in the constructor. Is it still visible to other threads?

katiex7
  • 863
  • 12
  • 23
  • 5
    Constructors implicitly include inline initializations like this. – Louis Wasserman Jan 08 '18 at 20:07
  • 1
    I've never said "setting the visibility in the constructor" @Lothar – katiex7 Jan 08 '18 at 20:09
  • No? Look at the title of your question. – Lothar Jan 08 '18 at 20:09
  • @LouisWasserman so are you implying that, this class and its set can be safely be published to other threads with full visibility? – katiex7 Jan 08 '18 at 20:09
  • The resulting bytecode is the same. This way you just avoid writing a constructor for simply initializing `set`. – Kayaman Jan 08 '18 at 20:12
  • 1
    "Visibility of final fields not set in constructor" vs "setting the visibility in the constructor" Two are different things. If you construct an object with final fields and set them inside the constructor, the JMM gives visibility to other threads when publishing that object, so as long as you don't let the this reference escape. What I was asking is, would this have the same effect even though you didn't specifically do something like public Foo(Set set) { set = set; } – katiex7 Jan 08 '18 at 20:12
  • @Kayaman sweet, so I guess you are implying yes to my question as well? – katiex7 Jan 08 '18 at 20:13
  • 1
    "Imply" sounds like there's a degree of uncertainty. – Kayaman Jan 08 '18 at 20:14
  • Well, I was looking for a yes to be sure. So may I ask if it's a yes? – katiex7 Jan 08 '18 at 20:16
  • Louis answered you, I answered you and Jim answered you with the duplicate explaining how it works. – Kayaman Jan 08 '18 at 20:17
  • okay, thank you all LouisWasserman, Jim Garrison and Kayaman – katiex7 Jan 08 '18 at 20:25

0 Answers0