简体   繁体   中英

Java- executor service shutdown at class level field

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)

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

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