如果仅在构造函数中编写Collection线程安全吗? [英] Is a Collection threadsafe if it's only written in the constructor?

查看:48
本文介绍了如果仅在构造函数中编写Collection线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这个课程

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

    public Foo() {
        bar.add("one");
        bar.add("two");
        bar.add("three");
    }

    public boolean contains(final String s) {
        return bar.contains(s);
    }
}

实例化 Foo 并从多个线程调用此对象的包含

Would it be threadsafe to instantiate Foo and call contains of this object from multiple threads?


  1. 对集合的引用是 private final 。没有人可以直接访问该集合。

  2. 唯一的写访问发生在构造函数中

  3. 在构造函数执行后,该集合将仅读取和读取

  1. The reference to the collection is private and final. No one can access directly the collection.
  2. The only write access occurs in the constructor
  3. After the constructor is executed, the collection will only read and not modified.

如果不修改,是否有Java替代Guava的不可变集合?

If not, is there an pure Java alternative to Guava's immutable collections?

推荐答案

只要

1,它是线程安全的)构造方法在完全构造引用之前不会泄漏它。

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

2)没有人可以访问集合。

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

3)没有可以创建子类的子集可以编辑集合。

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

不过,如果要实现此规则,请使用番石榴中的不可变集合,这样行为对于程序员来说是很明显的,并且然后可以安全地返回整个地图。我认为在纯Java中,您可以返回集合的不可修改视图。

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.

这篇关于如果仅在构造函数中编写Collection线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆