Do I need to synchronize a call to the interrupt method?

后端 未结 3 1894
予麋鹿
予麋鹿 2021-01-17 08:26

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

public void interrupt() {
          


        
3条回答
  •  花落未央
    2021-01-17 08:52

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

    Reasons:

    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.

    2. 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.

    3. 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.)

    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.

提交回复
热议问题