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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.