Thursday, September 8, 2016

JAVA MULTITHREADING: Thread Pool Using ExecutorService class

So, let's say you want to limit the number of threads executing at once.  This can be achieved through ExecutorService class.

Context:

  1. We have a runnable class, named Processor.
  2. Inside main(), we are declaring how many threads can run at once out of a thread pool that we'll create shortly.
  3. We create a thread pool by submitting all the threads to the executerService object.
  4. Then we shutdown() the executerService, which basically means it'll no longer accept submit() requests.
  5. Finally, we wait until the code execution completes for all threads. The timeout period is given as 1 day.
  6. Once done, we print saying all the tasks were completed.
Result:
It takes all the thread submit requests in, then starts 2 at once. Once one of the thread terminates, the third one is started. Basically, not more than 2 threads can remain active at once.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class App{
 public static void main(String[] args) {
  //This here defines the max. number of threads that can run at once
  ExecutorService executorService = Executors.newFixedThreadPool(2);
  
  //Through this loop, 5 threads shall be submitted to the executor.
  for(int i=0; i<5; i++){
   executorService.submit(new Processor(i));
  }
  
  //The executer shall no longer take any more submit requests
  executorService.shutdown();
  
  //A console output indicating the same
  System.out.println("All tasks submitted!");
  
  //Blocks until all tasks have completed execution after a shutdown request, 
  //or the timeout occurs, or the current thread is interrupted, whichever happens first.
  //Kinda like using join() method for threads
  try {
   executorService.awaitTermination(1, TimeUnit.DAYS);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  System.out.println("All tasks completed!");
 }
 
 
}

class Processor implements Runnable{
 private int id;
 
 public Processor(int id) {
  // TODO Auto-generated constructor stub
  this.id = id;
 }
 @Override
 public void run() {
  System.out.println("STARTING " + id);
  // TODO Auto-generated method stub
  
  try {
   Thread.sleep(5000);//<-- Pretending to do some work
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("COMPLETED " + id);
 }
 
}

No comments:

Post a Comment