首页 > 解决方案 > 使用 Spring @Value for Pool size 的线程池无法正常运行

问题描述

我有一个线程池,池大小的输入使用 spring 中的 @value 传递,其引用在 .properties 文件中。如下所示:

@Value("${project.threadPoolSize}")
private static int threadPoolSize;

private static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(threadPoolSize);

@PostConstruct
public void MasterProcessService() {
    try {
        LOGGER.debug("Entering processServices in MasterProcessThread ");

当我尝试使用注释值给出线程池大小时,它仅池化 1 个线程并执行睡眠操作,但稍后不会池化其他线程。

当我直接使用以下方法传递线程池大小时:

private static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(11);

它汇集所有线程并按照定义执行睡眠和运行状态。

任何人都可以帮助我在线程池大小中使用@Value 而不是直接定义一个数字吗?

标签: javamultithreadingspring-bootthreadpoolexecutor

解决方案


这一切都源于两个事实:

1 -@Value不适用于静态字段。如果你想用值填充它 - 不要让它成为静态的。

@Value("${project.threadPoolSize}")
private static int threadPoolSize;

2 -threadPool先创建静态变量,然后threadPoolSize再填充值(如果它还不是静态变量)。

如果您需要通过 为某个静态字段设置值@Value,您可以尝试如下操作:

private static ScheduledExecutorService threadPool;

@Value("${project.threadPoolSize}")
public void setThreadPool(Integer poolSize) {
    threadPool = Executors.newScheduledThreadPool(poolSize);
}

值注入将在启动时调用,并将调用该setThreadPool方法,该方法将为您初始化具有定义池大小的静态变量。


推荐阅读