


How does Spring Boot child thread access request information of the main thread?
Apr 19, 2025 pm 06:03 PMHow does Spring Boot child thread safely access main thread request information
In Spring Boot application, the controller layer initiates asynchronous tasks, and when the Service layer uses a new thread to process, it often faces the problem that the child thread cannot access the main thread HttpServletRequest
object. This is because HttpServletRequest
is bound to the main thread lifecycle and the child thread cannot be accessed directly. This article analyzes this problem and provides a reliable solution.
Problem description:
Use InheritableThreadLocal<httpservletrequest></httpservletrequest>
directly InheritableThreadLocal<httpservletrequest></httpservletrequest>
Passing HttpServletRequest
to the child thread is unreliable because the HttpServletRequest
object may have been destroyed after the main thread has processed the request. Even if the delivery is successful, it can cause memory leaks or other problems.
Error demonstration (code snippet):
The following code tries to pass HttpServletRequest
using InheritableThreadLocal
, but the child thread cannot get the correct user information:
Controller:
@RestController @RequestMapping("/test") public class TestController { private static InheritableThreadLocal<httpservletrequest> requestHolder = new InheritableThreadLocal(); @Autowired private TestService testService; @GetMapping("/check") public void check(HttpServletRequest request) { String userId = request.getHeader("userId"); System.out.println("main thread userId: " userId); requestHolder.set(request); new Thread(() -> testService.doSomething()).start(); System.out.println("main thread end"); } }</httpservletrequest>
Service layer:
@Service public class TestService { public void doSomething() { HttpServletRequest request = requestHolder.get(); String userId = request != null ? request.getHeader("userId") : "null"; System.out.println("child thread userId: " userId); } }
Solution:
Avoid passing HttpServletRequest
objects directly. The best practice is to extract necessary information (such as userId
) from HttpServletRequest
and then store this information in InheritableThreadLocal
.
Improved code example:
Controller:
@RestController @RequestMapping("/test") public class TestController { private static InheritableThreadLocal<string> userIdHolder = new InheritableThreadLocal(); @Autowired private TestService testService; @GetMapping("/check") public void check(HttpServletRequest request) { String userId = request.getHeader("userId"); System.out.println("main thread userId: " userId); userIdHolder.set(userId); new Thread(() -> testService.doSomething()).start(); System.out.println("main thread end"); } }</string>
Service layer:
@Service public class TestService { public void doSomething() { String userId = userIdHolder.get(); System.out.println("child thread userId: " userId); } }
This improved version only passes userId
, avoiding the life cycle of HttpServletRequest
object and ensuring that the child thread can reliably access the required data. According to actual needs, other necessary information can also be stored in InheritableThreadLocal
. Remember to clear the data in InheritableThreadLocal
in time after use to avoid memory leakage.
The above is the detailed content of How does Spring Boot child thread access request information of the main thread?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

In Unity, 3D physics engines and AI behavior trees can be implemented through C#. 1. Use the Rigidbody component and AddForce method to create a scrolling ball. 2. Through behavior tree nodes such as Patrol and ChasePlayer, AI characters can be designed to patrol and chase players.

Avoiding SQL injection in PHP can be done by: 1. Use parameterized queries (PreparedStatements), as shown in the PDO example. 2. Use ORM libraries, such as Doctrine or Eloquent, to automatically handle SQL injection. 3. Verify and filter user input to prevent other attack types.

The garbled problem in Java Chinese is mainly caused by inconsistent character encoding. The repair method includes ensuring the consistency of the system encoding and correctly handling encoding conversion. 1.Use UTF-8 encoding uniformly from files to databases and programs. 2. Clearly specify the encoding when reading the file, such as using BufferedReader and InputStreamReader. 3. Set the database character set, such as MySQL using the ALTERDATABASE statement. 4. Set Content-Type to text/html;charset=UTF-8 in HTTP requests and responses. 5. Pay attention to encoding consistency, conversion and debugging skills to ensure the correct processing of data.

Optimizing the performance of Hadoop distributed file system (HDFS) on CentOS systems can be achieved through a variety of methods, including adjusting system kernel parameters, optimizing HDFS configuration files, and improving hardware resources. The following are detailed optimization steps and suggestions: Adjust the system kernel parameters to increase the limit on the number of files opened by a single process: Use the ulimit-n65535 command to temporarily adjust. If it needs to take effect permanently, please edit the /etc/security/limits.conf and /etc/pam.d/login files. Optimize TCP parameters: Edit /etc/sysctl.conf file, add or modify the following content: net.ipv4.tcp_tw

For good reason, Blockdag focuses on buyer interests. Blockdag has raised an astonishing $265 million in 28 batches of its pre-sales As 2025 approaches, investors are steadily accumulating high-potential crypto projects. Whether it’s low-cost pre-sale coins that offer a lot of upside, or a blue chip network that prepares for critical upgrades, this moment provides a unique entry point. From fast scalability to flexible modular blockchain architecture, these four outstanding names have attracted attention throughout the market. Analysts and early adopters are watching closely, calling them the best crypto coins to buy short-term gains and long-term value now. 1. BlockDag (BDAG): 7 days left

Linux system restricts user resources through the ulimit command to prevent excessive use of resources. 1.ulimit is a built-in shell command that can limit the number of file descriptors (-n), memory size (-v), thread count (-u), etc., which are divided into soft limit (current effective value) and hard limit (maximum upper limit). 2. Use the ulimit command directly for temporary modification, such as ulimit-n2048, but it is only valid for the current session. 3. For permanent effect, you need to modify /etc/security/limits.conf and PAM configuration files, and add sessionrequiredpam_limits.so. 4. The systemd service needs to set Lim in the unit file

Custom Laravel user authentication logic can be implemented through the following steps: 1. Add additional verification conditions when logging in, such as mailbox verification. 2. Create a custom Guard class and expand the authentication process. Custom authentication logic requires a deep understanding of Laravel's authentication system and pay attention to security, performance and maintenance.
