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

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

    As long as this is accessed in a read only manner I think you should be safe. Also , java offers immutable versions of it's base collections exposed through static methods on the Collections class , so I would look at Collections.unmodifiableSet() .

    Also , while you add strings in your example, and strings themselves are immutable in java , you would be in trouble if you added mutable objects and then decided to modify/read them from different threads (you would need synchronized blocks in this case).

提交回复
热议问题