当前位置:网站首页>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
边栏推荐
- LVGL 8.2 Menu
- Halo effect - who says that those with light on their heads are heroes
- numpy笔记
- Scratch Castle Adventure Electronic Society graphical programming scratch grade examination level 3 true questions and answers analysis June 2022
- MySQL triggers
- Classify boost libraries by function
- Popular framework: the use of glide
- Digi重启XBee-Pro S2C生产,有些差别需要注意
- 關於miui12.5 紅米k20pro用au或者povo2出現問題的解决辦法
- Is BigDecimal safe to calculate the amount? Look at these five pits~~
猜你喜欢
Explain of SQL optimization
【C语言】指针笔试题
Opencv learning notes - linear filtering: box filtering, mean filtering, Gaussian filtering
Node mongodb installation
Query optimizer for SQL optimization
SqlServer函数,存储过程的创建和使用
Count the running time of PHP program and set the maximum running time of PHP
Transplant tinyplay for imx6q development board QT system
Red envelope activity design in e-commerce system
LVGL 8.2 Line wrap, recoloring and scrolling
随机推荐
The failure rate is as high as 80%. What are the challenges on the way of enterprise digital transformation?
PyTorch的自动求导机制详细解析,PyTorch的核心魔法
LVGL 8.2 Line
如何搭建一支搞垮公司的技术团队?
C language achievement management system for middle school students
Scratch Castle Adventure Electronic Society graphical programming scratch grade examination level 3 true questions and answers analysis June 2022
LVGL 8.2 keyboard
leecode学习笔记-约瑟夫问题
Solutions to the problems of miui12.5 red rice k20pro using Au or povo2
Alcohol driving monitoring system based on stm32+ Huawei cloud IOT design
Ali was laid off employees, looking for a job n day, headhunters came bad news
IO flow: node flow and processing flow are summarized in detail.
A collection of classic papers on convolutional neural networks (deep learning classification)
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
深度学习 神经网络案例(手写数字识别)
Comment configurer un accord
ES6 modularization
C language book rental management system
Wt588f02b-8s (c006_03) single chip voice IC scheme enables smart doorbell design to reduce cost and increase efficiency
Openresty current limiting