|
| 1 | +# 🖥️ Sharing QueryCountPerRequest Across Threads in Asynchronous Environments |
| 2 | + |
| 3 | +[한국어](README-java-asynchronous-environments.md) | **English** |
| 4 | + |
| 5 | +## 🖥️ Overview |
| 6 | + |
| 7 | +The Multi-Datasource-Query-Counter library counts database queries per API request. By default, it uses `@RequestScope` to ensure each request has its own counter. |
| 8 | +However, in asynchronous environments (`CompletableFuture`, `@Async`, WebFlux, etc.), execution switches to new threads, which cannot access the original request context, resulting in missed query counts. |
| 9 | + |
| 10 | +This guide explains how to properly share the `QueryCountPerRequest` object across threads in asynchronous environments. |
| 11 | + |
| 12 | +<br> |
| 13 | + |
| 14 | +## 🖥️ The Problem |
| 15 | + |
| 16 | +In a typical Spring application, a request is processed within a single thread. |
| 17 | +However, when using asynchronous code: |
| 18 | + |
| 19 | +1. Execution switches to a new thread. |
| 20 | +2. The new thread has a new context. |
| 21 | + |
| 22 | +So, the new thread cannot access the original request context. |
| 23 | + |
| 24 | +<br> |
| 25 | + |
| 26 | +## 🖥️ Solution: Using TaskDecorator |
| 27 | + |
| 28 | +Spring provides `TaskDecorator` which allows copying the request context to new threads before executing asynchronous tasks. |
| 29 | + |
| 30 | +### 1. Configure ThreadPoolTaskExecutor |
| 31 | + |
| 32 | +```java |
| 33 | +import org.springframework.context.annotation.Bean; |
| 34 | +import org.springframework.context.annotation.Configuration; |
| 35 | +import org.springframework.scheduling.annotation.EnableAsync; |
| 36 | +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; |
| 37 | +import org.springframework.web.context.request.RequestAttributes; |
| 38 | +import org.springframework.web.context.request.RequestContextHolder; |
| 39 | + |
| 40 | +import java.util.concurrent.Executor; |
| 41 | + |
| 42 | +@EnableAsync |
| 43 | +@Configuration |
| 44 | +public class AsyncConfig { |
| 45 | + |
| 46 | + @Bean(name = "asyncExecutor") |
| 47 | + public Executor asyncExecutor() { |
| 48 | + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); |
| 49 | + |
| 50 | + // Configure thread pool settings according to your application needs... (skip) |
| 51 | + |
| 52 | + // Set TaskDecorator to copy the request context to the new thread! |
| 53 | + executor.setTaskDecorator(task -> { |
| 54 | + RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); |
| 55 | + return () -> { |
| 56 | + try { |
| 57 | + RequestContextHolder.setRequestAttributes(requestAttributes); |
| 58 | + task.run(); |
| 59 | + } finally { |
| 60 | + RequestContextHolder.resetRequestAttributes(); |
| 61 | + } |
| 62 | + }; |
| 63 | + }); |
| 64 | + |
| 65 | + executor.initialize(); |
| 66 | + return executor; |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
| 70 | + |
| 71 | +### 2. Using CompletableFuture |
| 72 | + |
| 73 | +When using CompletableFuture directly, use the custom Executor: |
| 74 | + |
| 75 | +```java |
| 76 | +@Autowired |
| 77 | +@Qualifier("asyncExecutor") |
| 78 | +private Executor asyncExecutor; |
| 79 | + |
| 80 | +public CompletableFuture<List<User>> findAllUsersAsync() { |
| 81 | + return CompletableFuture.supplyAsync(() -> { |
| 82 | + return userRepository.findAll(); // Query count point. |
| 83 | + }, asyncExecutor); // Specify the custom executor. |
| 84 | +} |
| 85 | +``` |
| 86 | + |
| 87 | +### 3. Using @Async Annotation |
| 88 | + |
| 89 | +When using the @Async annotation, explicitly specify the configured Executor: |
| 90 | + |
| 91 | +```java |
| 92 | +@Async("asyncExecutor") // Specify the bean name explicitly. |
| 93 | +public CompletableFuture<User> findUserByIdAsync(Long id) { |
| 94 | + return CompletableFuture.completedFuture( |
| 95 | + userRepository.findById(id).orElse(null) // Query count point. |
| 96 | + ); |
| 97 | +} |
| 98 | +``` |
| 99 | + |
| 100 | +<br> |
| 101 | + |
| 102 | +## 🖥️ WebFlux/Reactor Environment |
| 103 | + |
| 104 | +(WIP) |
0 commit comments