【问题标题】:Executors thread stops after spring server thread response执行者线程在spring服务器线程响应后停止
【发布时间】: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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-06-24
      • 2020-01-23
      • 2011-02-17
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多