java - 使用 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 而不是直接定义一个数字吗?
解决方案
这一切都源于两个事实:
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
方法,该方法将为您初始化具有定义池大小的静态变量。
推荐阅读
- angular - Angular - 路由路径抛出控制台错误
- python - Mask R-CNN 中的预训练权重和初始化权重是什么?
- php - 尝试通过 CURL 发送消息后未经授权的 Discord 响应
- php - 按值和大小对多维数组进行排序
- java - 从应用程序到 Java 服务器的 Java Socket 连接
- reactjs - Redux - 未调用减速器
- applescript - 将删除的文件移动到文件夹 X,否则只需使用 Applescript 打开 X
- blazor-client-side - Blazor 的 OnInitializedAsync 事件在 DOM 完成之前触发
- azure-active-directory - Azure 应用程序网关 WAF:HTTP 错误 400。请求标头的大小太长
- python - 在 python spyder 中找不到模块“Tabula”