gpt4 book ai didi

java - 为什么并发练习书中的SafePoint类标记为@ThreadSafe?

转载 作者:行者123 更新时间:2023-12-02 06:00:23 24 4
gpt4 key购买 nike

在《Java Concurrency in Practice》一书中,您可以找到以下代码:

@ThreadSafe
public class SafePoint {
@GuardedBy("this") private int x, y;
private SafePoint(int[] a) { this(a[0], a[1]); }
public SafePoint(SafePoint p) { this(p.get()); }
public SafePoint(int x, int y) {
this.x = x;
this.y = y;
}
public synchronized int[] get() { return new int[] { x, y };
}
public synchronized void set(int x, int y) { this.x = x;
this.y = y;
}
}

这标记为@ThreadSafe

我非常确定这个类不是线程安全的(如果我正确理解这个术语的话)。

示例:

 SafePoint racePublishedSafePoint; // field

// thread 1:
racePublishedSafePoint = new SafePoint(1,1);

// thread 2:
SafePoint sp;
while(true){
SafePoint sp = racePublishedSafePoint;
if(sp != null) break;
}
System.out.println(sp.get()[0]);
System.out.println(sp.get()[1]);

我相信有几种可能的结果:

  1. 应用程序未完成
    否则
  2. 如果申请完成,我们可以看到
    a) 0 0
    b) 0 1
    c) 1 0
    d) 1 1

我说得对吗?

如果属实,为什么作者将该类标记为线程安全?我认为线程安全类 - 无需复杂分析即可在并发应用程序中使用的类。

作者想表达什么?

附注

我已阅读 Private constructor to avoid race condition

...我的主题不重复。

最佳答案

我同意OP的观点,即该示例似乎违反了对@ThreadSafe保证的通常理解。不安全的发布竞赛是非常真实的,当然,通过竞赛发布 SafePoint 时您会看到令人费解的行为。一些现实生活中的线程安全类在活泼的出版物中幸存下来(String 就是一个臭名昭著的例子),增加了困惑。

就 JCIP 的叙述而言,我手边没有纸质或电子副本,因此联系了 Doug Lea(主要作者之一),他说:

I think the part of confusion is in the JCIP text. I don't think @ThreadSafe covers publication races, or any other races that could be encountered during construction. Publication safety is treated separately.

Still, I can see how people could think otherwise. It is one of the reasons for us exploring always placing release fences in constructors.

Doug 谈论的最后一部分在 "All Fields Are Final" 中有简要描述。 ,包括动机、实验补丁和性能估计。

关于java - 为什么并发练习书中的SafePoint类标记为@ThreadSafe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55981577/

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