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

前端 未结 4 1345
攒了一身酷
攒了一身酷 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:47

    It is thread safe provided that

    1) The constructor does not leak a reference before its fully constructed.

    2) No one has any way to access the collection.

    3) No subclass can be created which can edit the collection.

    As a general rule though, if you want to implement this use an immutable collection from guava, that makes the behaviour explicit to the programmer, and it is then safe to return the whole map. I think that in pure java you can return an unmodifiable view of a collection.

提交回复
热议问题