Is happens-before transitive when calling Thread.start()?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-21 21:19:33

问题


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:


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)



来源:https://stackoverflow.com/questions/48255948/is-happens-before-transitive-when-calling-thread-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!