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

后端 未结 3 1890
予麋鹿
予麋鹿 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:37

    @xehpuk's question deserves more attention:

    Why would it need synchronization? And on which object?

    The whole point of synchronization---the only point---is to protect data from corruption. We use synchronization when it is impossible for one thread to advance the state of the program without creating a temporary invalid state that other threads must not be allowed to see.

    In that case, we synchronize the code block that creates the temporary, invalid state, and we must also synchronize every code block that ever looks at the state.

    So, when we talk about interrupting a thread, what states are we talking about?

    Well, without looking at the code, it seems like there would be only two: Not-interrupted and interrupted, and both of them are valid. There's no obvious invalid state to go through to get from one to the other: To get from not-interrupted to interrupted seems like one atomic operation. So, a reasonable programmer would expect that there's no need for synchronization.

    Of course, there might be some internal details that I have skipped over, but internal details should be hidden from the programmer. A reasonable programmer would expect that, if there is a need for synchronization, then it either would taken care of inside the interrupt() method, or else it would be very clearly documented as the caller's responsibility.

提交回复
热议问题