ExecutorService tutorial

The ExecutorService avaliable since java 1.5 is an Executor that provides the possibility to track the progress and manage termination of the asynchronous tasks. In the below examples we are going to look at how to provide the unit of code to be executed asynchronously to the ExecutorService. We will then do the shutdown of the ExecutorService.

1.  Create Runnable implementation

Create  a piece of code that will be executed by the Executor Service. For this we will have to create a class that implements Runnable interface. In the below tutorial we will only printout the name.
package com.programtak.executor.tutorial;
// author programtalk.com
public class MyRunnable implements Runnable {
	private String name;
	MyRunnable(String name) {
		this.name = name;
	public void run() {
		System.out.println("My name is :" + name);


2. Submit the Runnable to ExecutorService

Now we will see the code where we submit the above Runnable to the ExecutorService.  We are using a newFixedThreadPool so as to make the example simple. As the name says, it create a thread pool with fixed number of threads. So as to execute our submitted tasks we need to call executorService.shutdown(). And after that we can do some tasks or decide to wait for the executed threads to finish. To wait for the tasks we will use executorService.awaitTermination(1, TimeUnit.MINUTES). So we are waiting here for maximum of 1 minute. But be careful, because if the threads are still executing after the timeout has passed, the threads will still be executing. We can see this case in our next tutorial.

package com.programtak.executor.tutorial;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
// author programtalk.com
public class MyExecutor {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.submit(new MyRunnable("First"));
        executorService.submit(new MyRunnable("Second"));
        executorService.submit(new MyRunnable("Third"));
        try {
            executorService.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) 	 {


If you see the below output, it is a typical asynchronus tasks output which does not respect our order of submission and that is expected behaviour. You have little control over which code gets executed first.

My name is :First
My name is :Third
My name is :Second



Like this post? Don’t forget to share it!

Comments are closed, but trackbacks and pingbacks are open.