The essence of Deep Java threading interrupts and an overview of programming principles _java

Source: Internet
Author: User
Historically, Java has tried to provide a preemptive limit interrupt, but there are many problems, such as the discarded thread.stop, Thread.Suspend, and Thread.Resume described in the previous article. On the other hand, due to the robustness of Java application code, the threshold of programming is reduced, and the probability that programmers who are not aware of the underlying mechanism is unintentionally destroying the system is reduced.

Today, Java thread scheduling does not provide preemptive interrupts, but uses collaborative interrupts. In fact, the collaborative interruption, the principle is very simple, that is, polling a token to indicate the interruption, we can be implemented in any normal code.

For example, the following code:
volatile bool isinterrupted;
...
while (!isinterrupted) {
Compute ();
}
However, the above code issues are also obvious. When the compute execution time is longer, the interrupt cannot be responded to in time. On the other hand, using polling to check for flag variables, there is no way to interrupt thread blocking operations such as wait and sleep.

If you still use the above ideas, to allow interrupts to be responded to in a timely manner, you must check the tag variables at the bottom of the virtual machine for thread scheduling. Yes, that's exactly what the JVM does.

The following is an excerpt from Java.lang.Thread's source code:

public static Boolean interrupted () {
Return CurrentThread (). isinterrupted (True);
}
...
Private Native Boolean isinterrupted (Boolean clearinterrupted);

It can be found that isinterrupted is declared as a native method, depending on the implementation of the JVM's underlying.

Indeed, within the JVM, a break tag is indeed maintained for each thread. However, the application cannot access the interrupt variable directly, and you must do so in the following ways:

public class Thread {
Set interrupt Marks
public void interrupt () {...}
Gets the value of the interrupt token
public Boolean isinterrupted () {...}
Clears the interrupt mark and returns the value of the last interrupt mark
public static Boolean interrupted () {...}
}

Typically, the calling thread's interrupt method does not immediately cause an interrupt, but sets the interrupt tag inside the JVM. Therefore, by checking the interrupt tag, the application can do some special work or completely ignore the interrupt.

You might think that if the JVM only provides this rudimentary interrupt mechanism, it has little advantage over the way the application defines the interrupt variable and polls itself.

The main advantage of the internal interrupt variable in the JVM is that it provides a mechanism for simulating automatic "interrupt falling" in some cases.

When execution involves blocking calls that involve thread scheduling (such as wait, sleep, and join), the blocked thread throws the Interruptedexception "as fast as possible" if an interrupt occurs. Therefore, we can use the following code framework to handle thread blocking interrupts:
try {
Wait, sleep, or join
}
catch (Interruptedexception e) {
Some interrupt processing work
}
The so-called "as fast as possible," I guess the JVM is the thread scheduling scheduling gap check interrupt variable, speed depends on the implementation of the JVM and hardware performance.

However, the JVM does not automatically throw interruptedexception exceptions for some thread blocking operations. For example, some I/O operations and internal lock operations. For this type of operation, you can simulate interrupts in other ways:

1) asynchronous socket I/O in java.io

When reading and writing sockets, the Read and write methods of InputStream and OutputStream block the wait, but do not respond to Java interrupts. However, when the Close method of the socket is invoked, the blocked thread throws a SocketException exception.

2 asynchronous I/O implemented with selector

If the thread is blocked in Selector.select (in Java.nio.channels), invoking the Wakeup method can cause closedselectorexception exceptions.

3) Lock acquisition

If the thread is waiting to acquire an internal lock, we will not be able to interrupt it. However, using the lockinterruptibly method of the lock class, we can provide interrupt capability while waiting for the lock.
In addition, in a task-and-thread-separated framework, a task usually does not know which thread it will be invoked by, nor does it know the policy of the calling thread to handle the interrupt. Therefore, after the task has set the thread interrupt tag, it is not possible to ensure that the task is canceled. Therefore, the following two programming principles are:
1 Unless you know the thread's interrupt strategy, you should not interrupt it.

This principle tells us that we should not directly call the interrupt method of the Executer frame thread, and should use methods such as Future.cancel to cancel the task.

2 The task code should not guess the meaning of the interrupt on the execution thread.

This principle tells us that the general code should not be caught after the interruptedexception exception, but should continue to throw to the upper layer of code.

In a word, the non preemptive interrupt mechanism in Java requires us to change the traditional preemptive interrupt idea, and to use the corresponding principles and patterns to program the basic understanding of its essence.

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.