【发布时间】:2015-05-13 02:30:51
【问题描述】:
我正在尝试了解有效不可变类的安全发布。对于我的班级,我无法想出线程不安全的场景。我需要添加一些其他的安全防护吗?
澄清:容器元素是线程安全的
public class Container<E> {
private LinkedList<E> data;
public Container() {
this.data = new LinkedList<E>();
}
public Container(final Container<E> other) {
this.data = new LinkedList<E>(other.data);
}
public Container<E> add(E e) {
Container<E> other_cont= new Container<E>(this);
other_cont.data.add(e);
return other_cont;
}
public Container<E> remove() {
Container<E> other_cont= new Container<E>(this);
other_cont.data.remove(0);
return other_cont;
}
public E peek() {
if(this.data.isEmpty())
throw new NoSuchElementException("No element to peek at");
return this.data.get(0);
}
public int size() {
return this.data.size();
}
}
【问题讨论】:
-
如果元素本身是线程不安全的,则可能存在问题。例如,假设您有一个 Container
。理论上你可以调用 peek() 在两个单独的线程中检索相同的 LinkedList,然后你就有问题了。 -
为了争论,假设元素本身是线程安全的。
-
如果可以调用 add 或 remove 则不安全,并发调用可能会破坏双向链表。
-
@Ben 但是由于 add 和 remove 并没有修改列表本身,它怎么不安全?
-
对不起,你是对的。我误读了。如果您使用写时复制,那么它是安全的
标签: java multithreading thread-safety safe-publication