1. What is an asynchronous task
Whether it is in life or in a program, it can be roughly divided into two types: synchronous and asynchronous.
Synchronization: For example, if you go to eat Haidilao, you have to order the bottom of the pot first, then the dishes, then the waiter brings the bottom of the pot, then the dishes, and finally you can eat the dishes. This process must be done in order. .
Asynchronous tasks: Let’s go eat Haidilao. There are many people eating. There are many people in front of you. You may have to queue up and wait until you are in line before you can enter the restaurant. But what if you want to go to the toilet halfway? You have to queue up again when you come back. So there is a call system. You queue up to get a number first, and then you can go get a massage, watch a movie, go to the spa, buy a cup of milk tea... It's finally your turn. At this time, you will be notified that you are in line, and then you can enter. This process is asynchronous.
2. SpringBoot Async
At first I thought about opening a thread pool and throwing the tasks into the thread pool to complete.
Later I remembered that SpringBoot has a more convenient asynchronous framework Async
The code is also very simple. You only need to add @Async to the method that needs asynchronous execution, and add @EnableAsync to the SpringBoot startup class. That’s it
@Async public void task() { // do something }
3. Pitfall diary
Although the code is small, the pitfalls will not decrease as the amount of code decreases.
For the sake of convenience, I built a demo locally and directly uploaded the code
@RestController public class AsyncController { @Autowired private AsyncService asyncService; @GetMapping("/v1/say") public String sayV1() { asyncService.sayV1(); return "success1"; } @GetMapping("/v2/say") public String sayV2() { asyncService.sayV2(); return "success2"; } }
@Service public class AsyncService { public void sayV1() { try { Thread.sleep(3000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("hello world"); } @Async public void sayV2() { try { Thread.sleep(3000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("hello world"); } }
It is a very simple demo that provides two interfaces, /v1/say and /v2/say, one for synchronous execution , an asynchronous execution that simulates time-consuming tasks by sleeping for 3 seconds
Start normally without any problems. If it is executed synchronously, wait 3 seconds before the main thread will return. If it is executed asynchronously, it will return immediately and wait 3 seconds. Helloworld
will be output. However, when I added a breakpoint, a problem occurred.
I first added a breakpoint on the line that prints hello world. The effect is the same as the original one, except that it is blocked before printing, but it does not affect the return of the main thread.
Edit
But when I added a breakpoint where the method came in, I found that the main thread was actually blocked!
Edit
4. Solve
Various problem solving, @Async does not take effect, asynchronous tasks wait for the main thread to return, nothing happens Find effective solutions.
Later, a colleague reminded me, could it be a thread blocked by the debug function?
With the attitude of giving it a try, I found the debug configuration
Edit
The breakpoint can choose to block the jvm Or block the current thread. The default is to block the jvm.
Select suspend to Thread, and the main thread will no longer be blocked
The above is the detailed content of Java asynchronous task implementation and analysis. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function