当前位置:网站首页>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
边栏推荐
- Sqlserver functions, creation and use of stored procedures
- Query optimizer for SQL optimization
- PLC模拟量输入 模拟量转换FC S_ITR (CODESYS平台)
- LVLG 8.2 circular scrolling animation of a label
- Exploration and practice of eventbridge in the field of SaaS enterprise integration
- C language course design questions
- Yyds dry goods inventory # solve the real problem of famous enterprises: continuous maximum sum
- A keepalived high availability accident made me learn it again
- 产业互联网则具备更大的发展潜能,具备更多的行业场景
- [cloud native] how can I compete with this database?
猜你喜欢

scratch古堡历险记 电子学会图形化编程scratch等级考试三级真题和答案解析2022年6月
![[information retrieval] link analysis](/img/dc/4956e8e21d8ce6be1db1822d19ca61.png)
[information retrieval] link analysis

Memory management summary

Wt588f02b-8s (c006_03) single chip voice IC scheme enables smart doorbell design to reduce cost and increase efficiency

Summary of common problems in development

深度学习 网络正则化

No servers available for service: xxxx

Query optimizer for SQL optimization

开发中常见问题总结

Talk about 10 tips to ensure thread safety
随机推荐
[information retrieval] experiment of classification and clustering
LVGL 8.2 Line
Opencv learning notes - linear filtering: box filtering, mean filtering, Gaussian filtering
金额计算用 BigDecimal 就万无一失了?看看这五个坑吧~~
Is it safe to open an account online for stock speculation? Will you be cheated.
Xcode abnormal pictures cause IPA packet size problems
Data Lake (13): spark and iceberg integrate DDL operations
LVGL 8.2 keyboard
深度学习7 Transformer系列实例分割Mask2Former
UFO: Microsoft scholars have proposed a unified transformer for visual language representation learning to achieve SOTA performance on multiple multimodal tasks
Scratch Castle Adventure Electronic Society graphical programming scratch grade examination level 3 true questions and answers analysis June 2022
LVLG 8.2 circular scrolling animation of a label
SAIC Maxus officially released its new brand "mifa", and its flagship product mifa 9 was officially unveiled!
Chapter 16 string localization and message Dictionary (2)
C language achievement management system for middle school students
C language small commodity management system
Query optimizer for SQL optimization
Memory management summary
openresty 限流
LVGL 8.2 Line wrap, recoloring and scrolling