当前位置:网站首页>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 Draw label with gradient color
- Expose Ali's salary and position level
- Leetcode t49: grouping of alphabetic words
- [C language] Pointer written test questions
- MySQL stored procedure exercise
- 关于FPGA底层资源的细节问题
- 一文概览2D人体姿态估计
- Practical puzzle solving | how to extract irregular ROI regions in opencv
- A keepalived high availability accident made me learn it again
- 各大主流编程语言性能PK,结果出乎意料
猜你喜欢

LVGL 8.2 Line wrap, recoloring and scrolling

WT588F02B-8S(C006_03)单芯片语音ic方案为智能门铃设计降本增效赋能

一文概览2D人体姿态估计

Why do domestic mobile phone users choose iPhone when changing a mobile phone?

Talk about 10 tips to ensure thread safety

Data center concept

如何配和弦

Leecode learning notes - Joseph problem
![leetcode:6109. Number of people who know the secret [definition of DP]](/img/95/03e2606b249f26db052cf5075041c1.png)
leetcode:6109. Number of people who know the secret [definition of DP]

软件测试之测试评估
随机推荐
Deep learning 7 transformer series instance segmentation mask2former
C language small commodity management system
Leetcode 1200 minimum absolute difference [sort] The Path of leetcode for heroding
Implementation of macro instruction of first-order RC low-pass filter in signal processing (easy touch screen)
How to build a technical team that will bring down the company?
各大主流编程语言性能PK,结果出乎意料
潘多拉 IOT 开发板学习(RT-Thread)—— 实验3 按键实验(学习笔记)
Nowcoder reverse linked list
[MySQL from introduction to proficiency] [advanced chapter] (IV) MySQL permission management and control
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
Expose Ali's salary and position level
Classify boost libraries by function
openresty 重定向
Gin integrated Alipay payment
Count the running time of PHP program and set the maximum running time of PHP
Chapter 16 string localization and message Dictionary (2)
IO流:节点流和处理流详细归纳。
Five minutes per day machine learning: use gradient descent to complete the fitting of multi feature linear regression model
如何配和弦
The failure rate is as high as 80%. What are the challenges on the way of enterprise digital transformation?