coding made simple with some delicious cake

Java ExecutorService examples

This post will provide a brief description of the different types of ExecutorService available in java. This post will also include some Java ExecutorService examples.

What is the ExecutorService:

The executor service is provided by the java JDK because it helps simplifies the execution of asynchronous tasks. It provides a pool of threads and an API allowing you to submit tasks for execution.

Java ExecutorService examples:

CachedThreadPool:

The cached thread pool executor, will create a pool of threads to execute your task. The previously created threads will be available for reuse for any new tasks that need to be processed. Threads which have not been used for 60 seconds will be removed from the pool. This pool is good for short lived tasks that need to executed on a regular basis

Java

1

2

3

4

ExecutorService cachedThreadPool=Executors.newCachedThreadPool();

cachedThreadPool.execute(()->{

System.out.println("Running job");

});

FixedThreadPool:

The FixedThreadPool will create a thread pool of a fixed size you specify when creating the thread pool. If all the threads are being used, then any new task will wait until a thread is available. If a thread happens to die then a new Thread will be created.

Java

1

2

3

4

ExecutorService fixedThreadPool=Executors.newFixedThreadPool(10);

fixedThreadPool.execute(()->{

System.out.println("Running job");

});

SingleThreadExecutor:

The single thread executor will only have one Thread running at any point in time. If the thread is busy, then new tasks submitted will wait on a queue for processing. All messages using the executor will be processed sequentially. If the thread happens to die then a new thread will be created.

Java

1

2

3

4

ExecutorService fixedThreadPool=Executors.newSingleThreadExecutor();

fixedThreadPool.execute(()->{

System.out.println("Running job");

});

ScheduledThreadPool:

The scheduled thread pool allows you to schedule tasks to run on a consistent basis. For example I want task A to run every 5 seconds. If a thread dies then a new thread will be created in its place. You can scheudle a task to run with a fixed delay or at a fixed rate

SingleThreadScheduledExecutor:

The single thread scheduled executor will have a single thread scheduler running which allow you to schedule a task to run at a fixed rate or delay. Tasks will run sequentially meaning only one task will be running at a given time. If the thread dies then a new thread will be created.