executors线程在spring服务器线程响应后停止

pgx2nnw8  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(253)
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并结束后,线程立即挂起。
关于为什么会发生这种情况,有什么线索或解释吗?

vltsax25

vltsax251#

在这里,您可以创建无限多的任务

while(true) {
        workers.execute(() -> someAction(queue.take()));
 }

我想你刚刚得到 OutOfMemoryError 在某个时刻。试着替换 while(true) 具有 for (int i=0; i<num_of_threads_in_pool; i++)

相关问题