From 39c9333581e31c8c4bab98b9e4c603846a61185c Mon Sep 17 00:00:00 2001 From: huahua <610665905@qq.com> Date: Wed, 24 Jul 2024 11:20:56 +0800 Subject: [PATCH] =?UTF-8?q?fix=20=E7=BA=BF=E7=A8=8B=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../zbkj/common/config/ExecutorConfig.java | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/lxk-common/src/main/java/com/zbkj/common/config/ExecutorConfig.java b/lxk-common/src/main/java/com/zbkj/common/config/ExecutorConfig.java index 17bee222..f9dec106 100644 --- a/lxk-common/src/main/java/com/zbkj/common/config/ExecutorConfig.java +++ b/lxk-common/src/main/java/com/zbkj/common/config/ExecutorConfig.java @@ -1,5 +1,8 @@ package com.zbkj.common.config; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -7,11 +10,15 @@ import javax.annotation.PreDestroy; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; @Configuration public class ExecutorConfig { + private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class); + private ExecutorService executorService; + private final AtomicBoolean isShutdown = new AtomicBoolean(false); // @Bean // public ExecutorService executorService() { @@ -22,28 +29,36 @@ public class ExecutorConfig { // @PreDestroy // public void shutdown() { // executorService.shutdown(); // 不立即停止所有任务,但不再接受新任务 +// } + +// @Bean +// public ExecutorService executorService() { +// // 考虑根据实际情况调整线程池大小 +// int threadPoolSize = Runtime.getRuntime().availableProcessors() * 2; +// return Executors.newFixedThreadPool(threadPoolSize); // } @Bean - public ExecutorService executorService() { - // 考虑根据实际情况调整线程池大小 - int threadPoolSize = Runtime.getRuntime().availableProcessors() * 2; + public ExecutorService executorService(@Value("${executor.threadPoolSize:24}") int threadPoolSize) { + // 考虑根据配置文件或环境变量动态调整线程池大小 + // 这里的 threadPoolSize 通过 @Value 注解可以从应用的配置文件中读取,默认值为 24 return Executors.newFixedThreadPool(threadPoolSize); } @PreDestroy public void shutdown() { - if (executorService != null) { + if (!isShutdown.getAndSet(true)) { + executorService.shutdownNow(); // 尝试更彻底地关闭线程池 executorService.shutdownNow(); // 阻止新任务提交并尝试停止当前正在执行的任务 try { // 等待所有任务完成或等待一段时间 if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { - System.err.println("Pool did not terminate"); + logger.error("Pool did not terminate"); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // 重新设置中断状态 - System.err.println("Thread interrupted while waiting for the executor service to terminate."); + logger.error("Thread interrupted while waiting for the executor service to terminate.", ie); } } }