Home >Java >javaTutorial >Detailed explanation of Java examples: sub-thread task exception, main thread transaction rollback

Detailed explanation of Java examples: sub-thread task exception, main thread transaction rollback

WBOY
WBOYforward
2022-05-09 17:49:493536browse

This article brings you relevant knowledge about java, which mainly introduces the related issues about how to roll back the main thread transaction when an exception occurs in the sub-thread task, including the capture of exceptions. and transaction rollback, etc. Let’s take a look at them below. I hope it will be helpful to everyone.

Detailed explanation of Java examples: sub-thread task exception, main thread transaction rollback

## Recommended study: "

java video tutorial"

1. Ask questions

The main thread submitted a task to the thread pool. If an exception occurs during the execution of this task, how can the main thread catch the exception and roll back the transaction.

2. Main thread and sub-thread

Let’s take a look at the basics first. The following figure shows how the two threads run,

    The picture on the left shows that after the main thread starts a sub-thread, the two run independently without interfering with each other. Life and death are determined by fate. From now on, you and I are passers-by!
  • The picture on the right shows that the main thread starts a sub-thread and then continues to execute the main thread program logic, and obtains the execution result of the sub-thread by blocking at a certain node.

Detailed explanation of Java examples: sub-thread task exception, main thread transaction rollback

#For the problem raised above, the second method must be to solve the problem that the main thread can capture exceptions that occur during the execution of the child thread. I have to ask an interview question here, the difference between the two interfaces Callable and Runnable that implement threads:

public interface Callable<v> {
    V call() throws Exception;}</v>
public interface Runnable {
    public abstract void run();}
You can see that the call method has a return value, and the run method has no return value. In addition, the call method can throw exceptions, but the run method cannot. Obviously, in order to capture or know the running results of sub-threads, or running exceptions, we should implement it through the Callable interface.

Here we write an ExpSubThread class (sub-thread exception simulation class), implement the Callable interface, and directly throw a null pointer exception without doing too many actions.

public class ExpSubThread implements Callable {
    @Override
    public Object call() throws Exception {
        throw new NullPointerException();
    }}
3. Thread pool

When faced with thread tasks, we usually establish a thread pool in advance. The thread pool is a pre-planned collection of n thread resources. Its advantage is:

    When executing a task, it does not create a new thread, but uses the existing thread resources in the thread pool. When the task execution is completed, the thread resource is not destroyed, but the thread resource is returned to the thread pool. Therefore, to a certain extent, the resources consumed by thread creation and destruction are saved, and the purpose of thread resource reuse is achieved.
  • Because there is an upper limit on the size of the thread pool, another function of the thread pool is to avoid unlimited creation of threads and avoid system crashes caused by unlimited application resources. .
There are two commonly used thread pools, one is the one that comes with the JDK, and the other is the Spring thread pool. The latter is often used in the Spring environment, and they are similar. Here we use Spring API to build a thread pool.

public ThreadPoolTaskExecutor getThreadPool(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(100);  //线程池最大线程数
        executor.setCorePoolSize(50);//线程池核心线程数
        executor.setQueueCapacity(50);//任务队列的大小
        executor.setThreadNamePrefix("test_"); //线程前缀名
        executor.initialize(); //线程初始化
        return executor;}
4. Exception capture

The following is a test case I wrote, where it represents the program execution flow of the main thread

@Testvoid subThreadExceptionTest() {
        try{
            //新建子线程对象
            ExpSubThread expSubThread = new ExpSubThread();
            //构建线程池
            ThreadPoolTaskExecutor executor = getThreadPool();
            //提交子线程任务,submit方法
            Future future = executor.submit(expSubThread);
            //在这里可以做主线程的业务其他流程操作
            //阻塞等待子线程的执行结果
            Object obj = future.get();  
        }catch (Exception e){
            e.printStackTrace();
            //事务回滚
        }}
What needs to be noted here is Use the submit method to submit sub-thread tasks to the thread pool for execution. ThreadPoolTaskExecutor has two methods for executing thread tasks, one is the execute method and the other is the submit method.

    The execute method has no return value, so it is impossible to determine whether the task is successfully completed. The corresponding thread class implements the Runnable interface.
  • The submit method has a return value, returns a Future, and the corresponding thread class implements the Callable interface.

Detailed explanation of Java examples: sub-thread task exception, main thread transaction rollback

Future.get() method achieves the purpose of blocking the main thread, so that the execution result of the sub-thread task can be judged, and the get method can throw an exception.

    V get() throws InterruptedException, ExecutionException;
The picture below is the effect of the above test case program

e.printStackTrace();. From the picture you can see two Exception exceptions, one is that we are in the child thread A null pointer exception actively thrown in a simulated manner in the task, and another ExecutionException thrown by the get method caused by a null pointer.

Detailed explanation of Java examples: sub-thread task exception, main thread transaction rollback

5. Transaction rollback

As you have seen above, we have implemented the Callable interface through the

    thread class. The purpose of obtaining the thread return value or throwing an exception is achieved.
  • Submit can submit thread tasks to the thread pool, and can obtain the return value Future of the sub-thread execution result.
  • Future’s get() method can obtain child thread execution information, including exceptions thrown.
So now that we can sense or catch the exception information of the sub-thread in the main thread, is it too simple to roll back the transaction of the main thread in the next step?

  • jdbc just conn.rollback() realizes transaction rollback
  • Just use the @Transactional annotation in the spring environment.

Recommended study: "java video tutorial"

The above is the detailed content of Detailed explanation of Java examples: sub-thread task exception, main thread transaction rollback. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete