java - 执行者线程在spring服务器线程响应后停止
问题描述
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 并结束后立即挂起。
关于为什么会发生这种情况的任何线索或解释?
解决方案
在这里您可以创建无限数量的任务
while(true) {
workers.execute(() -> someAction(queue.take()));
}
我假设你只是OutOfMemoryError
在某个时候得到。尝试替换while(true)
为for (int i=0; i<num_of_threads_in_pool; i++)
推荐阅读
- amazon-web-services - 我无法在 AWS Aurora 集群中启用“公共访问”配置
- python - Word2Vec 训练的语料库中不可用的单词
- java - 没有数组的递归。IDE 打印正确的输出,FileWriter 没有
- python - 录制视频直到达到特定时间
- excel - VBA 我可以创建一个由一组工作表组成的 Iterable 对象吗?
- foreach - 如何在 SwiftUI 列表中使用 .focusedValue
- python - Python:在多台机器上使用相对路径
- mysql - NodeJs 和 MySql 连接中的异步/等待
- django - 无法在 Django UpdateView form_valid 中动态保存 user.is_active 或信号
- python - 运行 Python 脚本时出错,Web Scraping 代码