gpt4 book ai didi

java - 在 ConcurrentHashMap 中存储复杂对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:32 26 4
gpt4 key购买 nike

根据 Java 并发实践,下面的代码可以抛出断言错误:

如果发布线程以外的线程要调用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 中其他对象的对象,在多线程环境中,由于与上述相同的原因,此对象图上的某些更新是否有可能不同步对于上面的例子?

虽然对象图中的根节点将始终在所有线程的映射中更新,但是如果其他对象不是最终的或易变的,那么在根节点中被称为字段的其他对象呢?

最佳答案

回答我自己的问题,我应该在提问之前阅读完整的章节。这是本章后面的部分所说的:

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 中同步对可变对象的更改或者这些对象是不可变的。

关于java - 在 ConcurrentHashMap 中存储复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34278600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com