当前位置:网站首页>How to handle exceptions in multithreading?
How to handle exceptions in multithreading?
2022-07-04 14:50:00 【joshua317】
This paper is about joshua317 Original article , Reprint please indicate : Reprinted from joshua317 Blog How to handle exceptions in multithreading ? - joshua317 The blog of
One 、Thread Default exception handling for
Threads are not allowed to throw uncaught checked exception( such as sleep At the time of the InterruptedException), That is to say, each thread needs to put its own checked exception Dispose of . We can check it out Thread Class run() Method statement , There are no constraints on throwing exceptions on the method declaration .
//Thread Class
@Override
public void run() {
if (target != null) {
target.run();
}
}
//Runnable Interface
public abstract void run();


JVM This kind of design comes from such an idea :“ A thread is a code fragment that executes independently , The problem of thread should be solved by thread itself , Don't delegate to the outside .” Based on this design concept , stay Java in , Exception of thread method ( Whether it's checked exception still unchecked exception), Should be within the thread code boundary (run In the way ) Conduct try catch And get rid of . let me put it another way , We can't catch exceptions that escape from threads .
Two 、 How to handle uncaught exceptions
After an exception is thrown , If not captured , Will always throw up . Once the exception is Thread.run() After throwing , You can't catch exceptions in your program , Finally, only by JVM Capture .
package com.joshua317;
public class ThreadException {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
class MyThread extends Thread {
@Override
public void run()
{
System.out.println(" The thread of :" + Thread.currentThread().getName());
// Something goes wrong
int i = 1 / 0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Next, we try to catch exceptions , See if you can catch
package com.joshua317;
public class ThreadException {
public static void main(String[] args) {
try {
MyThread myThread = new MyThread();
myThread.start();
}catch (Exception e) {
System.out.println(" Catch the exception thrown by the thread !" + e.getMessage());
}
}
}
class MyThread extends Thread {
@Override
public void run()
{
System.out.println(" The thread of :" + Thread.currentThread().getName());
// Something goes wrong
int i = 1 / 0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

As a result, we found that , We try to be in main Method to catch the exception thrown in the thread , But it didn't work .
3、 ... and 、 that ,JVM How to deal with exceptions thrown in threads
see Thread Class source code , We can see that there is a dispatchUncaughtException Method , This method is used to handle exceptions thrown in the thread .JVM Would call dispatchUncaughtException Method to find the exception handler (UncaughtExceptionHandler), Handling exceptions .
/**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
// towards handler Dispatch uncaught exceptions . This method consists only of JVM call .
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
/**
* Returns the handler invoked when this thread abruptly terminates
* due to an uncaught exception. If this thread has not had an
* uncaught exception handler explicitly set then this thread's
* <tt>ThreadGroup</tt> object is returned, unless this thread
* has terminated, in which case <tt>null</tt> is returned.
* @since 1.5
* @return the uncaught exception handler for this thread
*/
// Get the handler, If it is not set, the current thread belongs to ThreadGroup
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}

UncaughtExceptionHandler Settings that must be displayed , Otherwise default to null. if null, The thread default handler, That is, the thread belongs to ThreadGroup.ThreadGroup It's a handler, see ThreadGroup Source code can be found ,ThreadGroup Realized Thread.UncaughtExceptionHandler Interface , And realize the default processing method . When the default uncaught exception handler handles , Would call System.err For the output , That is, print directly to the console .
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}

Thus we can see that , Final JVM Is to call the uncaught exception handler uncaughtException() Method to handle exceptions , And print directly to the console .
Four 、 How to customize thread exception handling
If we have to deal with exceptions ourselves , What to do ? Through the previous analysis , We already know that threads use the default uncaught exception handler to handle exceptions . Naturally, we can think of , Whether you can customize the uncaught exception handler , Override the default catch exception handler . actually ,Thead Indeed, a setUncaughtExceptionHandler Method , We just need to pass in the custom uncaught exception handler as a parameter .

Next, we customize the handling of thread exceptions
package com.joshua317;
public class ThreadException {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.setUncaughtExceptionHandler();
myThread.start();
}
}
class MyThread extends Thread {
@Override
public void run()
{
System.out.println(" The thread of :" + Thread.currentThread().getName());
// Something goes wrong
int i = 1 / 0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void setUncaughtExceptionHandler()
{
this.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println(" Catch the exception thrown by the thread :" + e.getMessage());
}
});
}
}

5、 ... and 、 Custom exception handling in thread pool
To customize exception handling , You only need to provide a customized UncaughtExceptionHandler. And in the process pool , How to batch set for all threads UncaughtExceptionHandler Well ? We know , Threads in the thread pool are created by thread factories . We can track ThreadPoolExecutor Source code of construction method , Finally, it is oriented to DefaultThreadFactory class , There is one in this class newThread() Method , This is the source of threads .
//ThreadPoolExecutor Class
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
//Executors Class
public static ThreadFactory defaultThreadFactory() {
return new DefaultThreadFactory();
}
//DefaultThreadFactory Class
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}



Found the source of thread creation , We can implement our own thread factory , And override the default newThread Method , Provide a for newly created threads UncaughtExceptionHandler, We can achieve our goal . because DefaultThreadFactory yes Executors The inner class of a class , We cannot inherit this class directly , Only the interface of this factory class can be implemented ——ThreadFactory Interface , To implement our own thread factory .
package com.joshua317;
import java.util.concurrent.ThreadFactory;
public class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread();
// Customize UncaughtExceptionHandler
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
return t;
}
}
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println(" Catch the exception thrown by the thread :" + e.getMessage());
}
}
This paper is about joshua317 Original article , Reprint please indicate : Reprinted from joshua317 Blog How to handle exceptions in multithreading ? - joshua317 The blog of
边栏推荐
- Xcode abnormal pictures cause IPA packet size problems
- 10. (map data) offline terrain data processing (for cesium)
- Scratch Castle Adventure Electronic Society graphical programming scratch grade examination level 3 true questions and answers analysis June 2022
- Industrial Internet has greater development potential and more industry scenarios
- Leetcode T48: rotating images
- STM32F1与STM32CubeIDE编程实例-MAX7219驱动8位7段数码管(基于GPIO)
- Five minutes per day machine learning: use gradient descent to complete the fitting of multi feature linear regression model
- 信号处理之一阶RC低通滤波器宏指令实现(繁易触摸屏)
- Opencv3.2 and opencv2.4 installation
- LVGL 8.2 List
猜你喜欢

为什么国产手机用户换下一部手机时,都选择了iPhone?

The failure rate is as high as 80%. What are the challenges on the way of enterprise digital transformation?
![[information retrieval] link analysis](/img/dc/4956e8e21d8ce6be1db1822d19ca61.png)
[information retrieval] link analysis

现代控制理论入门+理解

电商系统中红包活动设计

Programmers exposed that they took private jobs: they took more than 30 orders in 10 months, with a net income of 400000

【C语言】指针笔试题

Implementation of macro instruction of first-order RC low-pass filter in signal processing (easy touch screen)

5g TV cannot become a competitive advantage, and video resources become the last weapon of China's Radio and television

金额计算用 BigDecimal 就万无一失了?看看这五个坑吧~~
随机推荐
Ali was laid off employees, looking for a job n day, headhunters came bad news
Compile oglpg-9th-edition source code with clion
PyTorch的自动求导机制详细解析,PyTorch的核心魔法
LeetCode 1200 最小绝对差[排序] HERODING的LeetCode之路
内存管理总结
92. (cesium chapter) cesium building layering
Yyds dry goods inventory # solve the real problem of famous enterprises: continuous maximum sum
关于FPGA底层资源的细节问题
Partial modification - progressive development
關於miui12.5 紅米k20pro用au或者povo2出現問題的解决辦法
Solutions aux problèmes d'utilisation de l'au ou du povo 2 dans le riz rouge k20pro MIUI 12.5
C language achievement management system for middle school students
Query optimizer for SQL optimization
Ultrasonic distance meter based on 51 single chip microcomputer
03-存储系统
Nowcoder reverse linked list
LVGL 8.2 LED
LeetCode 1200 最小絕對差[排序] HERODING的LeetCode之路
Transplant tinyplay for imx6q development board QT system
Test evaluation of software testing