I have a fixed thread pool in my java web application.
App.aes = Executors.newFixedThreadPool(3);
It was used for executing asynchronous tasks. Those tasks can take hours to finish. So, if I need to do a application reloading, I need to check if there are asynchronous tasks running, if yes I need to store those tasks in the waiting queue to somewhere and restore them after a application reloading.
I did some test:
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(1);
for(int i=0; i< 5; i++){
final int c = i + 1;
es.submit(new Runnable(){
@Override
public void run() {
System.out.println("current running " + c);
try {
Thread.sleep(10000); // 10 sec
} catch (InterruptedException e) {
System.out.println("interrupted " + c);
}
}
});
}
Thread.sleep(15000);
List<Runnable> rems = es.shutdownNow();
System.out.println("Remaining " + rems.size());
System.out.println("--------- restore remaining task ----------");
es = Executors.newFixedThreadPool(1);
for(Runnable r : rems){
es.submit(r);
}
}
the output is:
current running 1
current running 2
interrupted 2
Remaining 4
--------- restore remaining task ----------
current running 3
current running 4
current running 5
current running 6
And this is not the result I am looking for. The interrupted tasks will not be recovered. And the API docs proved this:
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
how can we safely store and restore unfinished tasks in a java thread pool? My real task is fail-safe which means each task can be rerun again and again. And the order of being executed does not matter.
My web application is deployed on weblogic, and the thread pool is started up by a servlet, a ServletContextListener is registerd to shutdown the thread pool.
I am expecting two options:
option 1. No need to interrupt active tasks, wait them finish, and then save all those waiting tasks then shutdown thread pool.
pros: no need to worry about any unpredictable condition caused by interruption.
cons: this will need to wait all actively running task to be finished. depend on thread pool size and time cost of each task, the waiting time can be long.option 2. Interrupt active task, save all unfinished tasks then
shutdown thread pool.
option 1 is the idea solution for me.