What is the basic abstraction for creating threads in Java? Is it new Thread(new Runnable()) ? NO. It is Executors!
Decoupling is a good programming practice and it is better to separate thread creation from the application. Java's way of encapsulating these functions are known as executors. (Executors)
- Executor - simple interface used to submit new tasks
- ExecutorService - sub interface of Executor which supports life cycle management of both of the tasks and Executor itself.
- ScheduledExecutorService - sub interface of ExcecutorService which supports task scheduling.
ExecutorServiceThis has more features than Executor interface. Mainly it support thread pooling, return the result via Callable, shutting down the service.
This has following implementations in java.util.concurrent package.
Creating a ExecutorService can be done using Executors factory class.
ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(() -> System.out.println("running with executors"));
ScheduledExecutorServiceThis can be used to schedule given task after a given delay or periodically. Main methods are schedule, scheduleAtFixedRate, scheduledWithFixedDelay.
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.schedule(() -> System.out.println("running with a delay"), 1, TimeUnit.MINUTES);
Creating an ExecutorExecutors are created using Executors factory class in java.util.concurrent package. Which method we use is depending on our requirement.
- Executors.newSingleThreadExecutor - ExecutorService with a single thread to execute tasks.
- Executors.newCachedThreadPool - Creates a thread pool that creates new threads as needed. This creates a new thread if no thread is avaible and reuse an existing thread if they are avaible. Threads that have not been used for sixty seconds are terminated and removed from the cache.
- Executors.newFixedThreadPool - Created thread pool that reuses a fixed number of threads. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.
- Executors.newSingleThreadScheduledExecutor - ScheduledExecutorService with a single thread to execute tasks.
- Executors.newScheduledThreadPool - ScheduledExecutorService with a fixed length thread pool.
ExecutorService singleExecutorService = Executors.newSingleThreadExecutor(); ExecutorService fixedExecutorService = Executors.newFixedThreadPool(10); ExecutorService onDemandExecutorService = Executors.newCachedThreadPool(); ScheduledExecutorService singleScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); ScheduledExecutorService fixedScheduledExecutorService = Executors.newScheduledThreadPool(10);