首页 > 解决方案 > 执行者线程在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 并结束后立即挂起。

关于为什么会发生这种情况的任何线索或解释?

标签: javaspringmultithreadingspring-bootexecutorservice

解决方案


在这里您可以创建无限数量的任务

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

我假设你只是OutOfMemoryError在某个时候得到。尝试替换while(true)for (int i=0; i<num_of_threads_in_pool; i++)


推荐阅读