Does calling interrupt() on a thread create happen

2020-07-09 09:06发布

In other words I want to know if changing variable before interrupt is always visible when interrupt is detected inside interrupted thread. E.g.

private int sharedVariable;

public static void interruptTest() {
    Thread someThread = new Thread(() -> {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // Is it here guaranteed that changes before interrupt are always visible here?
            System.out.println(sharedVariable);
        }
    });
    someThread.start();
    Thread.sleep(1000);
    sharedVariable = 10;
    someThread.interrupt();
}

I tried to find answer in Java language specification and in Summary page of the java.util.concurrent package mentioned in Java tutorial but interrupt was not mentioned.

I know about volatile and other synchronize primitives but do I need them?

1条回答
一夜七次
2楼-- · 2020-07-09 09:20

Yes, interrupting a thread T2 from a thread T1 creates a happens-before relationship between T1 and T2, as described in the JLS 17.4.4. Synchronization Order:

If thread T1 interrupts thread T2, the interrupt by T1 synchronizes-with any point where any other thread (including T2) determines that T2 has been interrupted (by having an InterruptedException thrown or by invoking Thread.interrupted or Thread.isInterrupted).

Now that only implies that T1 synchronizes-with the detection of the interrupt T2, while you asked about happens-before. Luckily the former implies the latter from 17.4.5. Happens-before Order:

Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second.

If we have two actions x and y, we write hb(x, y) to indicate that x happens-before y.

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

So you are safe to access sharedVariable knowing that it has (at least) the value written by T1, even without volatile.

查看更多
登录 后发表回答