简体   繁体   English

在ConcurrentHashMap中存储复杂对象

[英]Storing complex object in ConcurrentHashMap

As per Java Concurrency in Practice below code can throw assertion Error: 根据Java Concurrency in Practice,下面的代码可以抛出断言错误:

If a thread other than the publishing thread were to call assertSanity, it could throw AssertionError 如果发布线程以外的线程调用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);
}

Question is: If I save, an object which refers to other objects in a ConcurrentHashMap, is there a possibility that certain updates on this object graph will not be in sync, in a multi-threaded environment due to same reasons as mentioned for above example? 问题是:如果我保存,引用ConcurrentHashMap中其他对象的对象,由于与上述示例相同的原因,在多线程环境中,此对象图上的某些更新可能不会同步?

Though root node in object graph will always be updated in map for all threads, but what about other objects which are referred as fields in root node, if these are not final or volatile ? 虽然对象图中的根节点将始终在地图中为所有线程更新,但是如果其他对象在根节点中被称为字段,那么它们是不是最终的还是易变的?

Answering my own question, I should have read complete chapter before asking question. 回答我自己的问题,在提出问题之前,我应该阅读完整的章节。 This is what later part of chapter says: 这是后面章节的内容:

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. 要安全地共享可变对象,必须安全地发布它们,并且要么是线程安全的,要么是锁定保护。

So using CHM or any thread safe collection is unsafe in a multithreaded environment, unless you synchronize changes to your mutable objects in CHM or these objects are immutable. 因此,在多线程环境中使用CHM或任何线程安全集合是不安全的,除非您将更改同步到CHM中的可变对象或这些对象是不可变的。

ConcurrentHashMap保证所有带有引用(链接到对象)的操作(保存在ConcurrentHashMap中)都是线程安全的,但是,当然,ConcurrentHashMap不能保证每个对象的线程安全,并且存储引用(链接)在ConcurrentHashMap中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM