【问题标题】:Thread Pool with Spring @Value for Pool size doesnt run properly使用 Spring @Value for Pool size 的线程池无法正常运行
【发布时间】:2019-05-14 20:27:53
【问题描述】:

我有一个线程池,池大小的输入使用 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 而不是直接定义一个数字?

【问题讨论】:

  • @Value 不适用于 static 字段。

标签: java multithreading spring-boot threadpoolexecutor


【解决方案1】:

这都是由于两个事实:

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 方法,该方法将为您初始化具有已定义池大小的静态变量。

【讨论】:

  • 我可以使用我的线程池大小来实现动态。如果是,如何获得它?
【解决方案2】:

Spring 不允许将值注入静态变量。请改用java.lang.Integer

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多