Is happens-before transitive when calling Thread.s

2020-07-25 05:41发布

Let's say we have a class

class Foo {
    int x;
    Foo() {
        x = 5;
    }
}

and some client code

public static void main(String[] args) {
    Foo foo = new Foo();
    new Thread(() -> {
        while (true) {
            new Thread(() -> {
                if (foo.x != 5) {
                    throw new AssertionError("this statement is false 1");
                }
                new Thread(() -> {
                    if (foo.x != 5) {
                        throw new AssertionError("this statement is false 2");
                    }
                }).start();
            }).start();
        }
    }).start();
}

Is it impossible for an AssertionError to be thrown because happens-before is transitive?

Even though Foo's x is not final, because of the happens-before guarantee of Thread.start(), a newly created thread from the thread that instantiated Foo, will see all the updates up to having called Thread.Start().

However, this thread also spawns many children threads, and since there is a happens-before relationship again, can we say that because of the transitive property of the happens-before, that AssertionError could never be thrown?

1条回答
劫难
2楼-- · 2020-07-25 06:17

Your question:

Since there is a happens-before relationship again, can we say that because of the transitive property of the happens-before, that AssertionError could never be thrown?

The answer is yes. As we can see in the JLS8 section 17.4.5. Happens-before Order:

  • If hb(x, y) and hb(y, z), then hb(x, z).

It is also given in the same section of the JLS that:

  • A call to start() on a thread happens-before any actions in the started thread.

So there is

  • hb(new Foo(), first-action-in-first-thread) and
  • hb(first-action-in-first-thread, first-action-in-first-assertion-thread)
  • hb(first-action-in-first-thread, first-action-in-second-assertion-thread)

which means that there is also:

  • hb(new Foo(), first-action-in-first-assertion-thread)
  • hb(new Foo(), first-action-in-second-assertion-thread)

(Since "For each thread t, the synchronization order of the synchronization actions (§17.4.2) in t is consistent with the program order (§17.4.3) of t.", I can omit the steps in-between, like the while(true) loop)

查看更多
登录 后发表回答