简体   繁体   中英

How to get pending Async task count in spring?

In my spring application, I've an Async method like the following in myService:

@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);
}

Here is how I'm creating the TaskExecutor bean

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

    return threadPoolTaskExecutor;
}

Inside my Controller I'm calling the Async method like the following:

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

Now I want to get the total number of pending Async tasks that have been added to queues. How can I get this? I've tried the following in my controller class but the TaskExecutor have no method that serves this purpose.

@Autowire
private TaskExecutor taskExecutor;

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

You could do:

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

But that would be an approximate and each of those methods actually uses a ReentrantLock for locking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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