How to do it...

  1. One important aspect of the behavior of the Executor interface you need to remember is that once created, it keeps running (waiting for new tasks to execute) until the Java process is stopped. So, if you would like to free memory, the Executor interface has to be stopped explicitly. If not shut down, forgotten executors will create a memory leak. Here is one possible way to make sure no executor is left behind:
        int shutdownDelaySec = 1;        ExecutorService execService =                        Executors.newSingleThreadExecutor();        Runnable runnable =  () -> System.out.println("Worker One did                                                       the job.");        execService.execute(runnable);        runnable =   () -> System.out.println("Worker Two did the                                                job.");        Future future = execService.submit(runnable); try  ...

Get Java 11 Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.