Reputation: 41
I am new to java programming and I am stuck at a problem. I am using Spring TaskExecutor
Interface for thread pool management. I have to extract content from different sources (Http, Files, Databse) in parallel so I have used the TaskExecutor
for this.
Now I want that once all threads are done with execution it should indicate the TaskExecutor
, also if they have not completed execution in 4 seconds that tasks should be terminated . So i am stuck with this problem. I tried using the callable interface with future but that causes task to be executed in sync but i need async. Please help me out.
Upvotes: 4
Views: 4059
Reputation: 206
You can also create a loop after the tasks creation and check for a timeout:
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Config.xml");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
taskExecutor.execute(new PrintTask("YOUR TASK ONE"));
taskExecutor.execute(new PrintTask("YOUR TASK TWO"));
double timeOutMs = 3000.0 ; // 3 seconds of maximum duration
double startTime = System.currentTimeMillis() ;
//check active thread, if zero then shut down the thread pool
for (;;) {
int count = taskExecutor.getActiveCount();
System.out.println("Active Threads : " + count);
if (System.currentTimeMillis() - startTime > timeOutMs) {
// Do something : its to late, cancel the tasks !
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count == 0) {
taskExecutor.shutdown();
break;
}
}
}
Upvotes: 1
Reputation: 9255
Use a method annotated @Async so that it runs in a separate process. Have it loop and keep track of the seconds since it began execution. If it goes over 4, have the loop exit and the thread will exit. Note that the @Async method needs to be in a different class from the method that spawns it.
Upvotes: 0