This commit is contained in:
huahua
2024-07-24 13:47:02 +08:00
parent 7cab85a021
commit 399c69ef73

View File

@@ -7,10 +7,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@Configuration
public class ExecutorConfig {
@@ -19,26 +18,45 @@ public class ExecutorConfig {
private ExecutorService executorService;
@Bean
@Bean(destroyMethod = "shutdown")
public ExecutorService executorService(@Value("${lxk.executor.threadPoolSize:12}") int threadPoolSize) {
// 考虑根据配置文件或环境变量动态调整线程池大小
// 这里的 threadPoolSize 通过 @Value 注解可以从应用的配置文件中读取,默认值为 12
return Executors.newFixedThreadPool(threadPoolSize);
// 使用自定义的拒绝策略
RejectedExecutionHandler rejectedExecutionHandler = new CustomRejectedExecutionHandler();
return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(threadPoolSize), new CustomThreadFactory(), rejectedExecutionHandler);
}
// 自定义拒绝策略,以记录被拒绝的任务
private static class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
logger.error("Task rejected by the executor: pool full or task exceeds maximum size.", r);
}
}
// 自定义线程工厂,可以用来统一线程的命名或其他特性
private static class CustomThreadFactory implements ThreadFactory {
private static final String THREAD_PREFIX = "Custom-Thread-";
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, THREAD_PREFIX + threadNumber.getAndIncrement());
return thread;
}
}
// 使用 @PreDestroy 注解确保在容器关闭时正确关闭线程池
@PreDestroy
public void shutdown() {
// 尝试更彻底地关闭线程池
public void shutdownExecutor() {
if (executorService != null) {
executorService.shutdownNow(); // 阻止新任务提交并尝试停止当前正在执行的任务
executorService.shutdown();
try {
// 等待所有任务完成或等待一段时间
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
logger.error("Pool did not terminate");
logger.warn("Executor did not terminate in the specified time.");
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // 重新设置中断状态
logger.error("Thread interrupted while waiting for the executor service to terminate.", ie);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Thread was interrupted while waiting for executor termination.", e);
}
}
}