Is a Collection threadsafe if it's only written in the constructor?

前端 未结 4 1350
攒了一身酷
攒了一身酷 2021-01-27 16:04

Assuming we had this class

final class Foo {
    private final Set bar = new HashSet<>();

    public Foo() {
        bar.add(\"one\");
              


        
4条回答
  •  臣服心动
    2021-01-27 16:55

    It depends on how the access to this object is published. While the bar Set is final and thus guaranteed to visible to all threads, the population of the map is not guaranteed to happen before the conclusion of constructor.

    This, however would be guaranteed to be thread safe regardless of how the object was created and made available.

    private final Set bar;
    
    public Foo() {
        bar = new HashSet(Arrays.asList("one", "two", "three"));
    }
    

    Testing initialization safety of final fields

    https://stackoverflow.com/a/23995782/676877

提交回复
热议问题