Java Concurrency (Basic knowledge)--java interrupt mechanism

Source: Internet
Author: User
Tags finally block

This article explains the creation, start, and stop of Java threads, talking about Java interrupts when it comes to stopping threads, and Java interrupts as a collaborative mechanism for stopping threads, which is intended to be explained in detail in the Java interrupt mechanism.

Search the Java interrupt mechanism on the Internet, found two good articles, respectively: Java Theory and Practice: processing interruptedexception and detailed analysis of the Java interrupt mechanism, recommended that you read carefully.

Interrupts are a collaborative mechanism

It is important to remember that interrupts are a collaborative mechanism. When a thread breaks another thread, the interrupted thread does not have to immediately stop what it is doing. Instead, a break is a polite request to another thread to stop what it is doing when it is willing and convenient. Some methods, such as Thread.Sleep (), take such requests very seriously, but not every method must respond to interrupts. You can ignore interrupt requests at will, but doing so can affect the response.

Interrupt Status

Each Java thread has a Boolean property associated with it that represents the interrupt state of the thread, and the thread class provides three methods for operating the interrupt state, including:

public static Boolean interrupted()

Test if the front thread has been interrupted. The interrupt state of the thread is purged by this method. In other words, if the method is called twice in a row, the second call will return False (except in the case where the current thread is interrupted again until the first call has cleared its break state and the second call has finished verifying the break state).

public booleanisinterrupted() Tests whether the thread has been interrupted. The interrupt state of the thread is not affected by the method.
public voidInterrupt() The thread is disconnected.

Of the three methods, the interrupt () method is the only way to set the interrupt state to true, and the other two methods are used to detect the current interrupt state.

Processing of interrupts

As a collaboration mechanism, the interrupt mechanism does not force the interrupted thread to be processed at a certain point. In fact, the interrupted thread only needs to handle interrupts at the appropriate time, and if there are no suitable points of point or even processing, then at the task-processing level, it will be the same as no interrupt method.

In the JDK, there are a lot of blocking methods in the declaration of the throw Interruptedexception exception, which implies that the method is interruptible, these methods will detect whether the current thread is interrupted, if so, immediately end the blocking method, and throws a Interruptedexception exception. If the program captures the interruptedexception that are thrown by these interruptible blocking methods or detects an interrupt, how can these interrupt messages be handled? There are generally the following two general principles:

    • If you encounter an interruptible blocking method that throws Interruptedexception, you can continue to throw the exception to the upper layer of the method call stack, and if an interrupt is detected, you can clear the interrupt state and throw interruptedexception. Makes the current method also an interruptible method.
    • If sometimes it is inconvenient to throw interruptedexception on the method, for example, the method signature on an interface to be implemented does not have throws interruptedexception on it, You can then capture the interruptedexception of the Interruptible method and reset the interrupt state through Thread.currentThread.interrupt (). This is true if the interrupt state is detected and cleared.

In general code, especially as a base class library, you should never swallow interrupts, that is, after capturing to Interruptedexception, do nothing in the catch, clear the interrupt state without resetting the interrupt state or throw interruptedexception and so on. Because swallowing the interrupt state causes the upper layer of the method call stack to get no such information.

Of course, there are always exceptions to this, when you know exactly who your method will be called, and the caller will not get into trouble because the interruption is swallowed up.

non-canceled tasks

Some tasks refuse to be interrupted, which makes them non-canceled. However, even non-canceled tasks should attempt to preserve the interrupt state, in case the code at the higher level of the call stack needs to process the interrupt after the non-canceled task ends. The following code shows a method that waits for a blocking queue until an available item appears in the queue, regardless of whether it is interrupted. To make it easier for others, it resumes the interrupt state in a finally block after the end, so as not to deprive the caller of the interrupt request of the right.

Public Task getnexttask (blockingqueue<task> queue) {    Boolean interrupted = false;    try {        while (true) {            try {                return Queue.take ()            } catch (Interruptedexception e) {                interrupted = True ;                Fall through and retry            }        }    } finally {        if (interrupted)            thread.currentthread (). Interrupt () ;    }}

Summarize

Interrupts are a collaborative mechanism that allows us to construct flexible thread cancellation policies that each thread can decide whether they can be canceled or not, and how to respond to interrupts, which can be deferred if the immediate return would compromise the integrity of the application.

Reference:

Java Theory and Practice: dealing with interruptedexception:http://www.ibm.com/developerworks/cn/java/j-jtp05236.html

Detailed analysis of the Java interrupt mechanism: http://www.infoq.com/cn/articles/java-interrupt-mechanism

Java Concurrency (Basic knowledge)--java interrupt mechanism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.