fix 线程配置

This commit is contained in:
huahua
2024-07-24 11:20:56 +08:00
parent 95cee69bc1
commit 39c9333581

View File

@@ -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);
}
}
}