Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of Java subthread task exception and main thread transaction rollback

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces Java child thread task exception and main thread transaction rollback problem how to solve the relevant knowledge, detailed and easy to understand, simple and fast operation, with certain reference value, I believe everyone read this Java child thread task exception and main thread transaction rollback problem how to solve the article will have some harvest, let's take a look at it.

I. Ask questions

The main thread submits 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?

Second, the main thread and child threads

Let's look at the basics first. The following figure shows how two threads run.

The diagram on the left shows that after the main thread starts a child thread, the two run independently of each other, and life and death have fate. From then on, you and I are passers-by!

The diagram on the right shows that the main thread continues to execute the program logic of the main thread after starting a child thread, and obtains the execution result of the child thread by blocking at a certain node.

For the problem posed above, it must be the second one to solve the main thread's ability to catch exceptions that occur during child thread execution. Here, we have to ask an interview question to realize the difference between the two interfaces of thread Callable and Runnable:

public interface Callable { V call() throws Exception;}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, and the run method cannot. Obviously, in order to catch or know the results of child threads, or run exceptions, we should implement them through the Callable interface.

Here we write an ExpSubThread class (subthread exception simulation class), implement the Callable interface, do not do too much action, directly throw a null pointer exception.

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

When faced with threaded tasks, we usually set up a thread pool in advance. A thread pool is a pre-planned collection of n thread resources. Its benefits are:

Instead of creating a new thread, a task executes using thread resources already in the thread pool. Task execution completion is not destroying threads, but returning thread resources to the thread pool. Therefore, to some extent, it saves the resources consumed by thread creation and destruction, and achieves the purpose of thread resource reuse.

Because there is an upper limit to the size of thread pool creation, thread pool also has another role is to avoid unlimited thread creation, to avoid the problem of system downtime caused by unlimited application resources.

There are two commonly used thread pools, one is JDK comes with, one is Spring thread pool, the latter is often used in Spring environment, the two are similar. Here we use the Spring API to build a thread pool.

public ThreadPoolTaskExecutor getThreadPool(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(100); //Maximum number of threads in the thread pool executor.setCorePoolSize(50);//Number of thread pool core threads executor.setQueueCapacity(50);//Size of task queue executor.setThreadNamePrefix("test_"); //Thread prefix name executor.initialize(); //thread initialization return executor;} 4. Exception catching

Here's a test case I wrote that represents the execution flow of the main thread

@Testvoid subThreadExceptionTest() { try{ //Create a new child thread object ExpSubThread expSubThread = new ExpSubThread(); //build thread pool ThreadPoolTaskExecutor executor = getThreadPool(); //submit child thread task, submit method Future future = executor.submit(expSubThread); //You can do other business process operations of the main process here //block waiting for child thread execution result Object obj = future.get(); }catch (Exception e){ e.printStackTrace(); //transaction rollback }}

Note here that the submit method is used to submit child thread tasks to the thread pool for execution. ThreadPoolTaskExecutor has two methods for executing threaded 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 has been successfully completed. The corresponding thread class implements the Runnable interface.

The submit method has a return value, returning a Future, and the corresponding thread class implements the Callable interface.

The Future.get() method achieves the goal of blocking the main thread so that it can determine the execution result of the child thread task, and the get method can throw exceptions.

V get() throws InterruptedException, ExecutionException;

The following diagram is the effect of the test case program e.printStackTrace(); above. From the diagram, you can see two Exception exceptions, one is the null pointer exception that we actively throw in the child thread task in a simulated way, and the other is the ExecutionException thrown by the get method caused by the null pointer.

V. Rollback of transactions

As you've seen above, we've passed

Thread class implements Callable interface, achieving the purpose of getting thread return value or throwing exception.

Submit can submit thread tasks to the thread pool, and can obtain the return value Future of the child thread execution results.

Future's get() method gets child thread execution information, including exception throws.

So now that we can sense or catch child thread exceptions inside the main thread, isn't it too easy to roll back transactions on the main thread next?

jdbc implements transaction rollback on conn.rollback()

The @Transactional annotation can be used in the spring environment.

About "Java child thread task exception and how to solve the main thread transaction rollback problem" The content of this article is introduced here, thank you for reading! I believe that everyone has a certain understanding of the knowledge of "Java sub-thread task exception and how to solve the main thread transaction rollback problem." If you still want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report