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:


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


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.


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.


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


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.

Similar posts:

  1. How to create a Thread in Java
  2. How to use Callable in Java
  3. Handle exception thrown by a callable


  1. ExecutorService API documentation

Leave a Reply