繁体   English   中英

如何在春季获得挂起的异步任务计数?

[英]How to get pending Async task count in spring?

在我的 spring 应用程序中,我在 myService 中有一个如下所示的Async方法:

@Async("threadPoolTaskExecutor")
public void exportObject(String id) {
    System.out.println("exporting " + id);
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("exported " + id);
}

这是我如何创建TaskExecutor bean

@Bean(name = "threadPoolTaskExecutor")
public TaskExecutor getTaskExecutor() {
    ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setCorePoolSize(5);
    threadPoolTaskExecutor.setMaxPoolSize(5);

    return threadPoolTaskExecutor;
}

在我的Controller我正在调用Async方法,如下所示:

for(int i = 0; i < 100; i++){
    myService.exportObject(i+"");
}

现在我想获取已添加到队列中的待处理异步任务总数。 我怎样才能得到这个? 我在我的控制器类中尝试了以下方法,但 TaskExecutor 没有用于此目的的方法。

@Autowire
private TaskExecutor taskExecutor;

public int getPendingTaskCount(){
    // taskExecutor.getPendingTaskCount(); // ?
}

可以这样做:

long result = threadPoolTaskExecutor.getThreadPoolExecutor().getTaskCount() -
              threadPoolTaskExecutor.getThreadPoolExecutor().getCompletedTaskCount();

但这只是一个近似值,每个方法实际上都使用 ReentrantLock 进行锁定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM