Java Executor Framework Tutorial and Example

By Arvind Rai, December 28, 2013
Java Executor Framework is a framework that manages threads to start, execute and terminate. Java Executor Framework provides different classes and methods that manage to create thread pool of fixed and variable sizes. Java Executor Framework provides Executor, ExecutorService and Executors in java.util.concurrent API. Executors creates the instance of ExecutorService that executes the submitted task. Executor can be overridden to implement execute() method according to our requirement. ExecutorService returns Future object that check the health of running task.

Java Executor Example

java.util.concurrent.Executor is an interface and introduced in JDK 5 and is the part of executor framework. Executor executes the submitted task. Executor gives the opportunity how we want to decouple the submitted task. To use Executor we need to create a class that will implement Executor interface. Executor can be implemented according to our task. If we want to implement Executor to run thread normally then we can do like
SimpleExecutor.java
class SimpleExecutor implements Executor {
    public void execute(Runnable r) {
        r.run();
    }
}
 
Now we consider one typical example in which we will run each thread sequentially. For that find a runnable thread.
RunnableThread.java
package com.concretepage; 
public class RunnableThread implements Runnable {
	String seq = null;
	public RunnableThread(String seq){
		this.seq = seq;
	}
    @Override
    public void run() {
        for (int cnt = 0; cnt < 5; cnt++) {
            System.out.println(seq+":" + cnt);
        }
    }
}
 
We have implemented an inner class SequentialExecutor. Using ArrayDeque, we are scheduling each task one by one.
ExecutorDemo.java
package com.concretepage;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.Executor;
public class ExecutorDemo {
	 public static void main(String[] args) {
		 RunnableThread t1 = new RunnableThread("One");
		 RunnableThread t2 = new RunnableThread("Two");
		 Executor executor = new SequentialExecutor();
		 executor.execute(t1);
		 executor.execute(t2);
	}
}
class SequentialExecutor implements Executor {
	   final Queue<Runnable> queue = new ArrayDeque<Runnable>();
	   Runnable task;
	   public synchronized void execute(final Runnable r) {
		   queue.offer(new Runnable() {
	       public void run() {
	         try {
	           r.run();
	         } finally {
	           next();
	         }
	       }
	     });
	     if (task == null) {
	       next();
	     }
	   }
	   private synchronized void next() {
	     if ((task = queue.poll()) != null) {
	             new Thread(task).start();	         
	       
	     }
	   }
}
 
Find the output in which we can pay attention to check that each task is executing one by one.
Executing thread one:0
Executing thread one:1
Executing thread one:2
Executing thread one:3
Executing thread one:4
Executing thread two:0
Executing thread two:1
Executing thread two:2
Executing thread two:3
Executing thread two:4
 

ExecutorService in Java

java.util.concurrent.ExecutorService has been introduced in JDK 5 and is the part of executor framework. ExecutorService is an Executor than can manage shutdown of executing subtask. It also provides Future object by which we check the progress of running task. ExecutorService has two method to terminate the task shutdown() and shutdownNow(). The difference between these two are that shutdown method will allow previously submitted task to execute and will accept no new task whereas shutdownNow method will not execute any task which has not started yet and even attempt to stop running task also. ExecutorService can be instantiated as below.
ExecutorService exService = Executors.newSingleThreadExecutor();
 

Executors in Java

java.util.concurrent.Executors has been introduced in JDK 5 and is the part of executor framework. Executors is a class that provides ExecutorService. ExecutorService has different methods like newCachedThreadPool(), newScheduledThreadPool() and newCachedThreadPool() that serves different purpose to create thread pool. newCachedThreadPool() creates a pool with no fixed size whereas newFixedThreadPool creates a fixed size pool. newScheduledThreadPool() creates a thread pool that can schedule thread after the given time.

Example of ExecutorService and Executors in Java

Find the simple example that will use both ExecutorService and Executors. We are using here newFixedThreadPool() that will return ExecutorService object.
ExecutorsDemo.java
package com.concretepage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorsDemo {
	 public static void main(String[] args) {
		 RunnableThread t = new RunnableThread("Executing thread");
		 ExecutorService exService = Executors.newFixedThreadPool(1);
		 exService.execute(t);
	}
}
 
Thread has been started by execute() method of ExecutorService. Find the output
 
Executing thread one:0
Executing thread one:1
Executing thread one:2
Executing thread one:3
Executing thread one:4
 
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us