根据实践中的Java Concurrency,以下代码可能引发断言错误:
如果要调用发布线程以外的线程
assertSanity,它可能会引发AssertionError
public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n != n)
throw new AssertionError("This statement is false.");
}
}
// Unsafe publication
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
问题是:如果我保存一个引用ConcurrentHashMap中其他对象的对象,则由于与上述示例相同的原因,在多线程环境中,该对象图上的某些更新可能不会同步?
虽然对象图中的根节点将始终在映射中针对所有线程进行更新,但是如果其他对象不是final或volatile,那么在根节点中称为字段的其他对象又如何呢?
解决方法:
在回答我自己的问题之前,我应该先完整阅读一章,然后再提出问题.这是本章后面的内容:
Mutable objects: If an object may be modified after construction, safe
publication ensures only the visibility of the as-published state.
Synchronization must be used not only to publish a mutable object, but
also every time the object is accessed to ensure visibility of
subsequent modifications. To share mutable objects safely, they must
be safely published and be either thread-safe or guarded by a lock.
因此,在多线程环境中使用CHM或任何线程安全集合都是不安全的,除非您将更改同步到CHM中的可变对象,或者这些对象是不可变的.
标签:multithreading,concurrency,java
来源: https://codeday.me/bug/20191119/2035130.html