在读取新值后读取陈旧值

Reading a stale value after a newer value was read

考虑这个例子。我们有:

int var = 0;

线程 A:

System.out.println(var);
System.out.println(var);

线程 B:

var = 1;

线程 运行 并发。是否可能出现以下输出?

1
0

即读取新值后读取原值。 var 不是易变的。我的直觉是不可能的。

var 的值被读取并且它是 1 时,它不会变回来。由于可见性或重新排序,此输出不会发生。可能发生的是 0 00 11 1.

这里要理解的重点是println涉及到同步。查看该方法内部,您应该在那里看到一个 synchronized 。这些块的效果是打印将按该顺序进行。虽然写入可以在任何时候发生,但不可能第一次打印看到 var 的新值而第二次打印看到旧值。因此,写入只能发生在两次打印之前、之间或之后。

除此之外,完全不保证写入可见,因为 var 未标记 volatile 也未以任何方式同步写入。

添加到其他答案:

使用 longdouble,写入可能不是原子的,因此前 32 位可能在最后 32 位之前可见,反之亦然。因此可以输出完全不同的值。

您使用的 System.out.println 在内部执行 synchronized(this) {...} 会使事情变得更糟。但即便如此,您的 reader 线程仍然可以观察到 1, 0,即:一个活泼的阅读。

到目前为止我还不是这方面的专家,但在阅读了 Alexey Shipilev 的大量 videos/examples/blogs 之后,我想我至少了解了一些东西。

JLS states 即:

If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

由于var的两次读取都在program order中,我们可以得出:

                (po) 
firstRead(var) ------> secondRead(var)
// po == program order

那句话还说这建立了一个happens-before订单,所以:

                (hb) 
firstRead(var) ------> secondRead(var)
// hb == happens before

但那是在“同一个线程”中。如果我们想推理多线程,我们需要查看 synchronization order。我们需要它,因为关于 happens-before order 的同一段说:

If an action x synchronizes-with a following action y, then we also have hb(x, y).

因此,如果我们在 program ordersynchronizes-with order 之间建立这个动作链,我们就可以推断出结果。让我们将其应用到您的代码中:

            (NO SW)                    (hb)
write(var) ---------> firstRead(var) -------> secondRead(var)

// NO SW == there is "no synchronizes-with order" here
// hb    == happens-before

这就是 happens-before consistencysame chapter 中发挥作用的地方:

A set of actions A is happens-before consistent if for all reads r in A, where W(r) is the write action seen by r, it is not the case that either hb(r, W(r)) or that there exists a write w in A such that w.v = r.v and hb(W(r), w) and hb(w, r).

In a happens-before consistent set of actions, each read sees a write that it is allowed to see by the happens-before ordering

我承认我对第一句话的理解非常模糊,这是 Alexey 对我帮助最大的地方,正如他所说:

Reads either see the last write that happened in the happens-before or any other write.

因为那里没有 synchronizes-with order,并且隐含地没有 happens-before order,允许读取线程通过竞争读取。 从而得到 1,而不是 0.


只要你介绍一个正确的synchronizes-with order,for example one from here

An unlock action on monitor m synchronizes-with all subsequent lock actions on...

A write to a volatile variable v synchronizes-with all subsequent reads of v by any thread...

图表发生变化(假设您选择 var volatile):

               SW                       PO
write(var) ---------> firstRead(var) -------> secondRead(var)

// SW == there IS "synchronizes-with order" here
// PO == happens-before

PO(程序顺序)通过我在 JLS 的这个答案中引用的第一句话给出了 HB(发生在之前)。而 SW 给出 HB 因为:

If an action x synchronizes-with a following action y, then we also have hb(x, y).

因此:

               HB                       HB
write(var) ---------> firstRead(var) -------> secondRead(var)

而现在happens-before order表示读取线程将读取“写入最后一个HB”的值,或者这意味着读取1然后0是不可能的。


我以 jcstress samples 为例并引入了一个小改动(就像您的 System.out.println 所做的那样):

@JCStressTest
@Outcome(id = "0, 0", expect = Expect.ACCEPTABLE, desc = "Doing both reads early.")
@Outcome(id = "1, 1", expect = Expect.ACCEPTABLE, desc = "Doing both reads late.")
@Outcome(id = "0, 1", expect = Expect.ACCEPTABLE, desc = "Doing first read early, not surprising.")
@Outcome(id = "1, 0", expect = Expect.ACCEPTABLE_INTERESTING, desc = "First read seen racy value early, and the second one did not.")
@State
public class SO64983578 {

    private final Holder h1 = new Holder();
    private final Holder h2 = h1;

    private static class Holder {

        int a;
        int trap;
    }

    @Actor
    public void actor1() {
        h1.a = 1;
    }

    @Actor
    public void actor2(II_Result r) {
        Holder h1 = this.h1;
        Holder h2 = this.h2;
        
        h1.trap = 0;
        h2.trap = 0;

        synchronized (this) {
            r.r1 = h1.a;
        }

        synchronized (this) {
            r.r2 = h2.a;
        }

    }

}

注意 synchronized(this){....} 不是初始示例的一部分。即使同步,我仍然可以看到 1, 0 作为结果。这只是为了证明即使 synchronized(来自 System.out.println 内部),你仍然可以获得 1 而不是 0.

我认为这里缺少的是那些线程 运行 在实际物理内核上的事实,我们这里几乎没有可能的变体:

  1. 所有线程运行在同一个核心上,那么问题就减少到那3条指令的执行顺序,在这种情况下我认为1,0是不可能的,println由于同步创建的内存屏障,执行是有序的,因此不包括 1,0

  2. A​​ 和 B 运行s 在 2 个不同的内核上,那么 1,0 看起来也不可能,只要 运行s 线程 A 的内核读取 1 , 之后就不可能读到 0 了,和上面一样 printlns 是有序的。

  3. 线程 A 在这两个 printlns 之间重新安排,因此第二个 println 在不同的核心上执行,与 B was/will 相同或在不同的第三个核心上执行。因此,当 2 个 printlns 在不同的内核上执行时,这取决于 2 个内核看到的值是什么,如果 var 不同步(不清楚 var 是否是其中的一个成员),那么这 2 个内核可以看到不同的 var 值,所以有可能是 1,0.

所以这是缓存一致性问题。

P.S。我不是 jvm 专家,所以这里可能还有其他事情在起作用。