当前位置:网站首页>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
边栏推荐
- [cloud native] how can I compete with this database?
- Transplant tinyplay for imx6q development board QT system
- A collection of classic papers on convolutional neural networks (deep learning classification)
- Wt588f02b-8s (c006_03) single chip voice IC scheme enables smart doorbell design to reduce cost and increase efficiency
- LVGL 8.2 Menu
- Leecode learning notes - Joseph problem
- C language personal address book management system
- numpy笔记
- C language course design questions
- Is BigDecimal safe to calculate the amount? Look at these five pits~~
猜你喜欢
IO流:节点流和处理流详细归纳。
Wt588f02b-8s (c006_03) single chip voice IC scheme enables smart doorbell design to reduce cost and increase efficiency
Stm32f1 and stm32subeide programming example -max7219 drives 8-bit 7-segment nixie tube (based on GPIO)
Pandora IOT development board learning (RT thread) - Experiment 3 button experiment (learning notes)
如何搭建一支搞垮公司的技术团队?
Leecode learning notes - Joseph problem
Gin integrated Alipay payment
PyTorch的自动求导机制详细解析,PyTorch的核心魔法
Test evaluation of software testing
Five minutes of machine learning every day: how to use matrix to represent the sample data of multiple characteristic variables?
随机推荐
Deep learning 7 transformer series instance segmentation mask2former
Solutions aux problèmes d'utilisation de l'au ou du povo 2 dans le riz rouge k20pro MIUI 12.5
The failure rate is as high as 80%. What are the challenges on the way of enterprise digital transformation?
【C语言】指针笔试题
第十六章 字符串本地化和消息字典(二)
Compile oglpg-9th-edition source code with clion
Query optimizer for SQL optimization
C language set operation
程序员自曝接私活:10个月时间接了30多个单子,纯收入40万
现代控制理论入门+理解
Expose Ali's salary and position level
flink sql-client. SH tutorial
First experience of ViewModel
Partial modification - progressive development
An overview of 2D human posture estimation
Digi重启XBee-Pro S2C生产,有些差别需要注意
深度学习 神经网络的优化方法
[C language] Pointer written test questions
Opencv3.2 and opencv2.4 installation
[MySQL from introduction to proficiency] [advanced chapter] (IV) MySQL permission management and control