Reputation: 647
I have ExecutorService at class level.
There is a rest point 'url'. So, user will call this API 'n' number of times per day.
How to shutdown the executor service if I define it class level?
CLASS LEVEL: (not sure how to shutdown executor service)
public class A {
private final ExecutorService executorService = Executors.newFixedThreadPool(3);
@GET("/url")
public void executeParallelTask() {
try {
executorService.submit(new Runnable() {
@Override
public void run() {
}
});
}
finally {
executorService.shutdown();
executorService.awaitTermination(12,TIMEUNIT.HOURS)
}
If I shutdown executor service in finally block, when next request comes at rest point, I’m getting Thread Pool size is empty and couldn’t handle the request.
I’m aware of method level like below.
public void executeParallelTask() {
executorService.submit(new Runnable() {
@Override
public void run() {
}
});
executorService.shutdown();
executorService.awaitTermination(12, TimeUnit.HOURS)
Upvotes: 2
Views: 936
Reputation: 299
You can do it in a shutdown hook.
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
if (executorService.isShutdown()) {
return;
}
log.debug("executorService shutting down...");
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
executorService.shutdownNow();
log.debug("executorService shutdown");
} catch (Throwable e) {
log.error(e, e);
}
}
});
}
Upvotes: 0