如果仅在构造函数中编写Collection线程安全吗? [英] Is a Collection threadsafe if it's only written in the constructor?
问题描述
假设我们有这个课程
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?
- 对集合的引用是
private
和final
。没有人可以直接访问该集合。 - 唯一的写访问发生在构造函数中
- 在构造函数执行后,该集合将仅读取和读取
- The reference to the collection is
private
andfinal
. No one can access directly the collection. - The only write access occurs in the constructor
- 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屋!