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

Java ExecutorService

We have seen Java Timer Class in our earlier tutorial to. ExecutorService will be better option than using Timer since configured with any number of threads but Timer has only one execution thread.
Another important point to ExecutorService is, if any run-time exception occurred inside TimerTask then current task will be canceled and rest will be continued in ExecutorService. Where as in Timer kill the Thread and following scheduled tasks won’t run further.
Lets see simple example's of how to run a repeated task at a specified interval using ExecutorService.
Java ExecutorService


Single Threaded:


public class JavaExecutorService {

 public static void main(String[] args) throws InterruptedException {
  
  TimerTask repeatedTask = new TimerTask() {
         public void run() {
             System.out.println("OUTPUT : " + Thread.currentThread().getName()  + " : Random Number : "+new Random().nextInt(1000));
         }
     };
     ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
     long delay  = 1000L;
     long period = 1000L;
     executor.scheduleAtFixedRate(repeatedTask, delay, period, TimeUnit.MILLISECONDS);
 }
}


OUTPUT:


OUTPUT : pool-1-thread-1 : Random Number : 608
OUTPUT : pool-1-thread-1 : Random Number : 62
OUTPUT : pool-1-thread-1 : Random Number : 161
OUTPUT : pool-1-thread-1 : Random Number : 141
OUTPUT : pool-1-thread-1 : Random Number : 954
OUTPUT : pool-1-thread-1 : Random Number : 565
OUTPUT : pool-1-thread-1 : Random Number : 839
.
.
.




By Setting Thread-pool Size:


public class JavaExecutorService {

 public static void main(String[] args) throws InterruptedException {
  
  TimerTask repeatedTask = new TimerTask() {
         public void run() {
             System.out.println("OUTPUT : " + Thread.currentThread().getName()  + " : Random Number : "+new Random().nextInt(1000));
         }
     };

     //Setting threadpool size to 5
     ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
     long delay  = 1000L;
     long period = 1000L;
     executor.scheduleAtFixedRate(repeatedTask, delay, period, TimeUnit.MILLISECONDS);
 }
}


OUTPUT:


OUTPUT : pool-1-thread-1 : Random Number : 562
OUTPUT : pool-1-thread-1 : Random Number : 207
OUTPUT : pool-1-thread-2 : Random Number : 912
OUTPUT : pool-1-thread-1 : Random Number : 165
OUTPUT : pool-1-thread-3 : Random Number : 676
OUTPUT : pool-1-thread-2 : Random Number : 956
OUTPUT : pool-1-thread-2 : Random Number : 987
OUTPUT : pool-1-thread-2 : Random Number : 866
OUTPUT : pool-1-thread-2 : Random Number : 331
OUTPUT : pool-1-thread-3 : Random Number : 183
OUTPUT : pool-1-thread-3 : Random Number : 669
OUTPUT : pool-1-thread-3 : Random Number : 617
OUTPUT : pool-1-thread-3 : Random Number : 719
OUTPUT : pool-1-thread-3 : Random Number : 757
OUTPUT : pool-1-thread-3 : Random Number : 728
OUTPUT : pool-1-thread-3 : Random Number : 77
OUTPUT : pool-1-thread-5 : Random Number : 66
OUTPUT : pool-1-thread-2 : Random Number : 64
OUTPUT : pool-1-thread-4 : Random Number : 643
.
.
.




Java Thread Pool with Executor Framework

 

Java Thread pool manages the pool of threads which are under runnable state. Thread pools contains list of all Threads in queue which are waiting to get executed. Also Thread pool can be described as collection of Runnable Objects or instance. Thread pool will be constantly running and are checking the work query for new work or Thread to be added into the pool. If there are new work or Thread to be added into the pool and executed through Thread Pool. In Java Thread class itself provides a method, e.g. execute(Runnable r) to add a new Runnable object to the work queue and execute() method will take on executing each thread in the pool.

The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination. Suppose if you want to use 1 thread pool with only 1 thread which executes several runnables you can use the Executors.newSingleThreadExecutor() method.


public class MyRunnableClass implements Runnable {

 private int value;

 MyRunnableClass(int value) {
  this.value = value;
 }

 @Override
 public void run() {
  int total = 0;
  for (int i = 1; i < value; i++) {
   total += i;
  }
  System.out.println(Thread.currentThread().getName() + " : " + total);  
 }
}


public class ThreadPoolTest {

 public static void main(String[] args) {
  // Thread pool size set as "5"
  ExecutorService executor = Executors.newFixedThreadPool(5);
  // Total 25 threads we are creating
  for (int i = 1; i <= 25; i++) {
   Runnable worker = new MyRunnableClass(i);
   executor.execute(worker);
  }
  executor.shutdown();
  System.out.println("All Threads finished...");
 }
}


OUTPUT:


pool-1-thread-1 : 0
pool-1-thread-1 : 15
pool-1-thread-1 : 21
pool-1-thread-1 : 28
pool-1-thread-1 : 36
pool-1-thread-1 : 45
pool-1-thread-1 : 55
pool-1-thread-1 : 66
pool-1-thread-1 : 78
pool-1-thread-1 : 91
pool-1-thread-1 : 105
pool-1-thread-1 : 120
pool-1-thread-1 : 136
pool-1-thread-1 : 153
pool-1-thread-1 : 171
pool-1-thread-1 : 190
pool-1-thread-1 : 210
pool-1-thread-1 : 231
pool-1-thread-1 : 253
pool-1-thread-1 : 276
pool-1-thread-1 : 300
All Threads finished...
pool-1-thread-3 : 3
pool-1-thread-4 : 6
pool-1-thread-2 : 1
pool-1-thread-5 : 10