Showing posts with label Thread pool example. Show all posts
Showing posts with label Thread pool example. Show all posts

Sunday, 9 March 2014

shutdownNow : Immediate shutdown

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

class WorkerThread implements Runnable{
 String taskName;

 WorkerThread(String taskName){
  this.taskName = taskName;
 }

 public String toString(){
  return taskName;
 }

 public void run(){
  try{
   Thread t1 = Thread.currentThread();
   System.out.println(t1.getName() + " executing the task " + taskName);
   t1.sleep(1000);
   System.out.println(t1.getName() + " completed the task " + taskName);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.*;

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  WorkerThread tasks[] = new WorkerThread[10];
  for(int i=0; i<10; i++){
   tasks[i] = new WorkerThread("task" + i);
   exec.execute(tasks[i]);
  }

  List<Runnable> l1 = exec.shutdownNow();
  exec.awaitTermination(10, TimeUnit.SECONDS);
  System.out.println("Waiting Threads are ");
  Iterator i1 = l1.iterator();
  while(i1.hasNext()){
   System.out.println(i1.next());
  }
 }
}

Sample Output
pool-1-thread-2 executing the task task1
pool-1-thread-1 executing the task task0
pool-1-thread-3 executing the task task2
java.lang.InterruptedException: sleep interrupted
java.lang.InterruptedException: sleep interrupted
java.lang.InterruptedException: sleep interrupted
Waiting Threads are
task3
task4
task5
task6
task7
task8
task9
   
awaitTermination() Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Executor exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
Above statement create a thread pool of size 3. So it can run 3 tasks at a time, Since 3 threads are reside in the pool.

exec.submit(tasks[i])
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the run method of the Runnable Object.




RejectedExecutionException                                                 Check whether threadpool shutdown or not                                                 Home

ExecutorService : shutdown()

void shutdown()
Initiates shut down of threads, once all the initiated tasks are executed. No new tasks are accepted once the shutdown initiated.

class WorkerThread implements Runnable{
 String taskName;

 WorkerThread(String taskName){
  this.taskName = taskName;
 }

 public void run(){
  try{
   Thread t1 = Thread.currentThread();
   System.out.println(t1.getName() + " executing the task " + taskName);
   t1.sleep(1000);
   System.out.println(t1.getName() + " completed the task " + taskName);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class SimpleThreadPool{
 public static void main(String args[]){
  ExecutorService exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  WorkerThread tasks[] = new WorkerThread[10];
  for(int i=0; i<10; i++){
   tasks[i] = new WorkerThread("task" + i);
   exec.execute(tasks[i]);
  }
  exec.shutdown();
 }
}
  
Sample Output
pool-1-thread-1 executing the task task0
pool-1-thread-4 executing the task task3
pool-1-thread-5 executing the task task4
pool-1-thread-2 executing the task task1
pool-1-thread-3 executing the task task2
pool-1-thread-1 completed the task task0
pool-1-thread-1 executing the task task5
pool-1-thread-4 completed the task task3
pool-1-thread-4 executing the task task6
pool-1-thread-5 completed the task task4
pool-1-thread-5 executing the task task7
pool-1-thread-3 completed the task task2
pool-1-thread-3 executing the task task8
pool-1-thread-2 completed the task task1
pool-1-thread-2 executing the task task9
pool-1-thread-4 completed the task task6
pool-1-thread-1 completed the task task5
pool-1-thread-5 completed the task task7
pool-1-thread-3 completed the task task8
pool-1-thread-2 completed the task task9

Executor exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
Above statement create a thread pool of size 5. So it can run 5 tasks at a time, Since 5 threads are reside in the pool.

exec.submit(tasks[i])
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the run method of the Runnable Object.



ExecutorService interface                                                 RejectedExecutionException                                                 Home

ExecutorService

ExecutorService is in java.util.concurrent package.

ExecutorService extends the Executor interface. Executor interface has only one method execute() in it.

ExecutorService Interface provides several features like shutdown the pool of threads, once they are done with their tasks execution, Blocks until all tasks have completed execution after a shutdown request etc.,

class WorkerThread implements Runnable{
 String taskName;

 WorkerThread(String taskName){
  this.taskName = taskName;
 }

 public void run(){
  try{
   Thread t1 = Thread.currentThread();
   System.out.println(t1.getName() + " executing the task " + taskName);
   t1.sleep(1000);
   System.out.println(t1.getName() + " completed the task " + taskName);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}
   
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class SimpleThreadPool{
 public static void main(String args[]){
  ExecutorService exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  WorkerThread tasks[] = new WorkerThread[10];
  for(int i=0; i<10; i++){
   tasks[i] = new WorkerThread("task" + i);
   exec.execute(tasks[i]);
  }
 }
}

Sample Output
pool-1-thread-2 executing the task task1
pool-1-thread-1 executing the task task0
pool-1-thread-3 executing the task task2
pool-1-thread-4 executing the task task3
pool-1-thread-5 executing the task task4
pool-1-thread-2 completed the task task1
pool-1-thread-3 completed the task task2
pool-1-thread-3 executing the task task6
pool-1-thread-4 completed the task task3
pool-1-thread-4 executing the task task7
pool-1-thread-5 completed the task task4
pool-1-thread-5 executing the task task8
pool-1-thread-1 completed the task task0
pool-1-thread-1 executing the task task9
pool-1-thread-2 executing the task task5
pool-1-thread-4 completed the task task7
pool-1-thread-3 completed the task task6
pool-1-thread-5 completed the task task8
pool-1-thread-2 completed the task task5
pool-1-thread-1 completed the task task9

Above statement create a thread pool of size 5. So it can run 5 tasks at a time, Since 5 threads are reside in the pool. In the above program, once the tasks execution finished, program simply waits, since the thread in the pool are not shutdown.

Executor exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
Above statement create a thread pool of size 5. So it can run 5 tasks at a time, Since 5 threads are reside in the pool.

exec.submit(tasks[i])
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the run method of the Runnable Object.




Check the cancellation status                                                 Shut down thread pool                                                 Home

Saturday, 8 March 2014

Callable Interface

Callable interface has one method call in it, it is just like run method of Runnable interface. But the main difference is, run method won't return any value where as call method returns a value.

In Some situation, it is necessary to return a value from a task and throw some exception in abnormal situations. But the run method in Runnable interface won't return any value and can't throw any exception. Java solve that problem by providing call method in Callable interface, call method returns any object and can throw an exception.

V call() throws Exception
Computes a result, or throws an exception if unable to do so. Returns the computed result.

CallableTask.java
import java.util.concurrent.*;
import java.util.*;

public class CallableTask implements Callable{
 String name;

 CallableTask(String name){
  this.name = name;
 }

 public String call(){
  try{
   Thread.sleep(1000);
  }
  catch(Exception e){
  }
  return (new Date() + " :: " + name);
 }
}

SimpleThreadPool.java
import java.util.concurrent.*;
import java.util.*;

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  List<Future<String>> l1 = new ArrayList<Future<String>> ();
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  CallableTask tasks[] =new CallableTask[10];

  for(int i=0; i<5; i++){
   tasks[i] = new CallableTask("task" + i);
   Future<String> future = exec.submit(tasks[i]);
   System.out.println("Submit the task " + i);
   l1.add(future);
  }

  exec.shutdown();
  exec.awaitTermination(10, TimeUnit.SECONDS);

  for(Future f1 : l1){
   System.out.println(f1.get());
  }
  System.out.println("Execution Completed");
 }
}

Output
Submit the task 0
Submit the task 1
Submit the task 2
Submit the task 3
Submit the task 4
Sat Mar 08 10:40:17 IST 2014 :: task0
Sat Mar 08 10:40:17 IST 2014 :: task1
Sat Mar 08 10:40:17 IST 2014 :: task2
Sat Mar 08 10:40:18 IST 2014 :: task3
Sat Mar 08 10:40:18 IST 2014 :: task4
Execution Completed

 ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())
Statement creates a thread pool of 3 threads.

exec.submit(tasks[i])
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the call method of the Callable Object.

exec.awaitTermination(10, TimeUnit.SECONDS)
Block the execution of the current thread for atmost 10 seconds, untill all the tasks finsishes. If all the tasks finishes before 10 seconds, it unblocks and proceed next statements executions.  
  



Executor Interface                                                 Runnable vs Callable                                                 Home

Executor Interface

Executor is in java.util.concurrent package.

Executor interface has one method execute(), all the class that implements this interface provides the implementation for this method.

void execute(Runnable command)
Executes the given command at some time in the future. Depends on the Executor implementation, this method can execute in a pooled thread, new thread or calling thread.

ThreadPoolExecutor class implements Executor interface, will see the use of execute() by below example.

WorkerThread.java
class WorkerThread implements Runnable{
 String taskName;

 WorkerThread(String taskName){
  this.taskName = taskName;
 }

 public void run(){
  try{
   Thread t1 = Thread.currentThread();
   System.out.println(t1.getName() + " executing the task " + taskName);
   t1.sleep(1000);
   System.out.println(t1.getName() + " completed the task " + taskName);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}

SimpleThreadPool.java
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class SimpleThreadPool{
 public static void main(String args[]){
  Executor exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  WorkerThread tasks[] = new WorkerThread[10];
  for(int i=0; i<10; i++){
   tasks[i] = new WorkerThread("task" + i);
   exec.execute(tasks[i]);
  }
 }
}

Output
pool-1-thread-2 executing the task task1
pool-1-thread-1 executing the task task0
pool-1-thread-3 executing the task task2
pool-1-thread-4 executing the task task3
pool-1-thread-5 executing the task task4
pool-1-thread-2 completed the task task1
pool-1-thread-3 completed the task task2
pool-1-thread-3 executing the task task6
pool-1-thread-4 completed the task task3
pool-1-thread-4 executing the task task7
pool-1-thread-5 completed the task task4
pool-1-thread-5 executing the task task8
pool-1-thread-1 completed the task task0
pool-1-thread-1 executing the task task9
pool-1-thread-2 executing the task task5
pool-1-thread-4 completed the task task7
pool-1-thread-3 completed the task task6
pool-1-thread-5 completed the task task8
pool-1-thread-2 completed the task task5
pool-1-thread-1 completed the task task9

Executor exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

Above statement create a thread pool of size 5. So it can run 5 tasks at a time, Since 5 threads are reside in the pool.

exec.submit(tasks[i])
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the run method of the Runnable Object.

After executing the tasks also program waits for execution, since the threads are not shut downed. They are waiting in the thread pool for new tasks.   
   






Thread Pools                                                 Callable Interface                                                 Home

Thread Pools

Thread creation is not comes for free. It includes overhead of creation of thread, assigning a stack to it, and destroy once thread done with its execution. Instead of using frequent short lived threads, use Thread pooling. You can create a pool of threads and each thread in the pool is waiting for a task to execute. When a task is assigned to a thread in the thread pool, it starts executing the task, once it finishes the task execution, instead of destroying, it go back to the thread pool and waits for another task to execute. With this approach no need to create a new thread for every new task.

Below example demonstrates the use of Thread pools.

WorkerThread.java
class WorkerThread implements Runnable{
 String taskName;

 WorkerThread(String taskName){
  this.taskName = taskName;
 }

 public void run(){
  try{
   Thread t1 = Thread.currentThread();
   System.out.println(t1.getName() + " executing the task " + taskName);
   t1.sleep(1000);
   System.out.println(t1.getName() + " completed the task " + taskName);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}

SimpleThreadPool.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class SimpleThreadPool{
 public static void main(String args[]){
  ExecutorService executors = Executors.newFixedThreadPool(5);
  WorkerThread tasks[] = new WorkerThread[10];
  
  for(int i=0; i<10; i++){
   tasks[i] = new WorkerThread("task" + i);
   executors.execute(tasks[i]);
  }
  executors.shutdown();
 }
}

Sample Output
pool-1-thread-1 executing the task task0
pool-1-thread-3 executing the task task2
pool-1-thread-4 executing the task task3
pool-1-thread-5 executing the task task4
pool-1-thread-2 executing the task task1
pool-1-thread-1 completed the task task0
pool-1-thread-3 completed the task task2
pool-1-thread-3 executing the task task5
pool-1-thread-1 executing the task task6
pool-1-thread-2 completed the task task1
pool-1-thread-2 executing the task task7
pool-1-thread-5 completed the task task4
pool-1-thread-5 executing the task task8
pool-1-thread-4 completed the task task3
pool-1-thread-4 executing the task task9
pool-1-thread-3 completed the task task5
pool-1-thread-1 completed the task task6
pool-1-thread-2 completed the task task7
pool-1-thread-5 completed the task task8
pool-1-thread-4 completed the task task9

WorkerThread is a class that implements Runnable interface. Created 10 Runnable tasks and assign it to the thread pool to execute.

ExecutorService executors = Executors.newFixedThreadPool(5);
Above statement creates a fixed thread pool of size 5, I.e, it has 5 threads in it waiting for tasks to execute.

executors.execute(tasks[i])
executes the given task, by assigning it ti the thread in the Task shared pool. If all the thread are busy in executing other tasks, then it waits until some thread is free to run this task.

executors.shutdown()
Once all the tasks assigned to the threads in the thread pool finished, then it initialize orderly shutdown of threads.


TimeUnit timedJoin                                                 Executor Interface                                                 Home