本文介绍了我是否需要同步对中断方法的调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java SE 7 中查询JavaDocs和 Thread.interrupt()方法的源代码这个:

Consulting the JavaDocs and the source code of the Thread.interrupt() method in Java SE 7 I found this:

public void interrupt() {
    if (this != Thread.currentThread())
        checkAccess();

    synchronized (blockerLock) {
        Interruptible b = blocker;
        if (b != null) {
            interrupt0();           // Just to set the interrupt flag
            b.interrupt(this);
            return;
        }
    }
    interrupt0(); //1, Outside of the synchronized block
}

//...

private native void interrupt0();

可以看出, // 1的本机方法调用在同步块之外。那么,如果不将 interrupt()方法调用到 synchronized 块中,是否安全?

As can be seen, the native method invocation at //1 is outside of the synchronized block. So, is it safe if don't put a call to the interrupt() method into a synchronized block?

Thread t;
//something else
t.interrupt(); //Not in a synchronized block

它是否是线程安全的?如果超过1个线程试图同时中断它怎么办?原生方法 interrupt0 将如何表现呢?

Will it be thread-safe? What if more than 1 thread will try to interrupt it simultaneously? How will the native method interrupt0 behave then?

推荐答案

我会说是的...它是线程安全的。

I would say yes ... it is thread-safe.

理由:


  1. 如果应用程序需要在 synchronized 块中调用 interrupt(),那么规范( javadoc)会这样说,并且还说出需要同步的对象以获得线程安全性。实际上,javadoc对此没有任何说明。

  1. If it was necessary for applications to call interrupt() in a synchronized block, then the the spec (the javadoc) would say so, and also say what object you needed to synchronize on to get thread-safety. In fact, the javadoc says nothing about this.

如果应用程序需要调用 interrupt() synchronized 块中,然后Oracle Java Tutorial on Concurrency会提到它。它没有。

If it was necessary for applications to call interrupt() in a synchronized block, then the Oracle Java Tutorial on Concurrency would mention it on this page. It doesn't.

如果需要在 Thread 对象上进行外部同步才能使 interrupt()调用线程安全,然后很难解释为什么该方法也在进行内部同步。 (如果有必要,他们可以/将会使整个方法同步。)

If external synchronization on the Thread object was necessary to make the interrupt() call thread-safe, then it is hard to explain why the method is doing internal synchronization as well. (They could / would have made the entire method synchronized if it was necessary.)

上述证据是(IMO)虽然不是绝对的证据,但令人信服。如果你想证明 interrupt()是线程安全的,你可以通过彻底分析 interrupt0()。我没有查看本机代码,但我希望 interrupt0 在内部是线程安全的,这足以使中断方法线程安全。

The above evidence is (IMO) convincing, though not absolute proof. If you wanted proof that interrupt() is thread-safe, you would get it by a thorough analysis of the native code implementation for interrupt0(). I haven't looked at the native code, but I would expect that interrupt0 is internally thread-safe, and that that is sufficient to make the interrupt method thread-safe.

这篇关于我是否需要同步对中断方法的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:27
查看更多