Java ExecutorService

Java ExecutorService is a JDK tool to let the programmer use the thread pool conveniently, submit and manage the asynchronized tasks. ExecutorService is an interface and Java provided the factory static class Executors for users to get different instances with different thread pool mode.

private final ExecutorService executor = Executors.newFixedThreadPool(10); //Fixed numer of threads, factory pattern. i.e. new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
private final ExecutorService executor = Executors.newSingleThreadExecutor(); //Single thread
private final ExecutorService executor = Executors.newCachedThreadPool(); //Flexible number of threads, 60 seconds life, always create new thread; if all threads are busy and max number of threads have been created, the new task will be put into the queue
Future<ReturnType> future = executor.submit(lambda); //submit the task to the executor and return immediately; see Java Functional Interface for lambda
future.cancel(isInterruptAllowed); //try to cancel the task; if the task has started, it could be interrupted;
future.get(); //get the result of ReturnType; it is a synchronized call; the code will wait here until the execution finishes
future.isDone(); // check if the task has been done
executor.execute(lambda); //just let the thread to run the task but you would not be able to track the progress or cancel it.
List<Future<ReturnType>> futures = executor.invokeAll(List<Callable<ReturnType>>(lambda)); //invoke all tasks in threads if multiple threads are available
executor.shutdown(); //stop accepting new tasks and the existing tasks will be finished before shutting down
List<Runnable> notRunTasks = executor.shutdownNow(); //try to shutdown executor immediately but no guarantee; the to be executed tasks are returned and user can make action on them in discretion.
//there are more methods, but the above ones are pretty commonly used
 
//another similar way
FutureTask<Object> m_futureTask = new FutureTask<>(lambda)
Executors.newSingleThreadExecutor().submit(m_futureTask) //create new job
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License