【发布时间】:2021-07-09 14:46:56
【问题描述】:
ControllerService {
LinkedBlockingQueue<String> queue;
ExecutorService workers;
@PostConstruct
public void init() {
queue = new LinkedBlockingQueue<>();
workers = Executors.newFixedThreadPool(10);
Executors.singleThreadedExecutor().execute(() -> {
while(true) {
workers.execute(() -> someAction(queue.take()));
}
})
}
public void method1(String name) {
// some actions
queue.put(name);
// some actions
}
}
Controller {
ControllerService controllerService;
@PostMapping("/api1")
public ResponseEntity<String> api1(@PathVariable String name) {
controllerService.method1(name);
return ResponseEntity.of("success");
}
}
这里的问题是someAction 需要 5-15 秒才能完成。 API /api1 在几毫秒内完成。这里发生的情况是,有时workers 线程在调用线程(负责服务器 API 调用的线程)返回 ResponseEntity 并结束后立即挂起。
关于为什么会发生这种情况的任何线索或解释?
【问题讨论】:
标签: java spring multithreading spring-boot executorservice