How to solve the problem of high concurrency InterruptedException in java
Preface
InterruptedException may not be as simple as you think!
When we call the wait() method of a Java object or the sleep() method of a thread, we need to catch and handle the InterruptedException exception. If we improperly handle InterruptedException, unexpected consequences will occur!
Program Case
For example, in the following program code, the InterruptedTask class implements the Runnable interface. In the run() method, the handle of the current thread is obtained, and in the while(true) loop, Use the isInterrupted() method to detect whether the current thread is interrupted. If the current thread is interrupted, exit the while(true) loop. At the same time, in the while(true) loop, there is also a line of Thread.sleep(100) code and capture InterruptedException exception.
The entire code is as follows.
package io.binghe.concurrent.lab08; /** * @author binghe * @version 1.0.0 * @description 线程测试中断 */ public class InterruptedTask implements Runnable{ @Override public void run() { Thread currentThread = Thread.currentThread(); while (true){ if(currentThread.isInterrupted()){ break; } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
The original intention of the above code is to check whether the thread has been interrupted through the isInterrupted() method, and if it is interrupted, exit the while loop. Other threads interrupt the execution thread by calling the interrupt() method of the execution thread. At this time, the interrupt flag bit of the execution thread is set, so that currentThread.isInterrupted() returns true, so that the while loop can be exited.
This seems to be no problem! But is this really the case? We create an InterruptedTest class for testing, the code is as follows.
package io.binghe.concurrent.lab08; /** * @author binghe * @version 1.0.0 * @description 测试线程中断 */ public class InterruptedTest { public static void main(String[] args){ InterruptedTask interruptedTask = new InterruptedTask(); Thread interruptedThread = new Thread(interruptedTask); interruptedThread.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } interruptedThread.interrupt(); } }
We run the main method as shown below.
Problem Analysis
The above code clearly calls the thread's interrupt() method to interrupt the thread, but it has no effect. The reason is that when the run() method of the thread is executed, it is blocked on sleep(100) most of the time. When other threads interrupt the execution thread by calling the interrupt() method of the execution thread, InterruptedException will be triggered with a high probability. Exception, when the InterruptedException exception is triggered, the JVM will clear the interrupt flag bit of the thread at the same time. Therefore, the currentThread.isInterrupted() judged in the run() method at this time will return false, and the current while loop will not exit. .
Now that the problem analysis has been cleared, How to interrupt the thread and exit the program?
Problem Solving
The correct way to handle it should be after catching the exception in the while(true) loop in the run() method in the InterruptedTask class Reset the interrupt flag bit, so the correct code for the InterruptedTask class is as follows.
package io.binghe.concurrent.lab08; /** * @author binghe * @version 1.0.0 * @description 中断线程测试 */ public class InterruptedTask implements Runnable{ @Override public void run() { Thread currentThread = Thread.currentThread(); while (true){ if(currentThread.isInterrupted()){ break; } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); currentThread.interrupt(); } } } }
As you can see, we have added a new line of code in the catch code block that captures the InterruptedException exception.
currentThread.interrupt();
This allows us toafter catching the InterruptedException exception, we can reset the interrupt flag bit of the thread, thereby interrupting the currently executing thread.
We run the main method of the InterruptedTest class again, as shown below.
Summary
Be careful when handling InterruptedException. If an InterruptedException is thrown when calling the interrupt() method of the execution thread to interrupt the execution thread, When the InterruptedException exception is triggered, the JVM will clear the interrupt flag bit of the execution thread at the same time. At this time, when the isInterrupted() method of the execution thread is called, false will be returned.
At this time, the correct way to handle it is to capture the InterruptedException exception in the run() method of the execution thread and reset the interrupt flag bit (that is, in the catch code block that captures the InterruptedException exception, re-call the current Thread's interrupt() method).
The above is the detailed content of How to solve the problem of high concurrency InterruptedException in java. For more information, please follow other related articles on the PHP Chinese website!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
