Java — Thread Pools (Executor Framework) | Code Factory

Index Page : Link

Donate : Link

WordPress Blog : Link

  • Creating a new thread for every job may create performance on memory problems, to overcome this we should go for Thread Pool.
  • Thread pool is a pool of already created threads, ready to do out job.
  • Java 1.5v introduces thread pool framework to implement thread pools. Thread Pool also know as executor framework.
  • We can create a thread pool as foolows.
ExecutorService service = Executors.newFixedThreadPool(3);
  • We can submit a Runnable job by using a submit method .
  • We can shutdown executor service by using shutdown method .
package com.example.thread;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author code.factory
*
*/
public class ExecutorTest {
public static void main(String... args) {
PrintJob jobs[] = {
new PrintJob("Narendra"),
new PrintJob("Amit"),
new PrintJob("Yogi"),
new PrintJob("Rupani"),
new PrintJob("Mukesh"),
new PrintJob("Anil"),
};
ExecutorService service = Executors.newFixedThreadPool(3);
for(PrintJob job : jobs) {
service.submit(job);
}
service.shutdown();
}
}
class PrintJob implements Runnable {
String name;
public PrintJob(String name) {
this.name = name;
}

public void run() {
System.out.println(name + " job started by thread " + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}

Output :

Narendra job started by thread pool-1-thread-1
Yogi job started by thread pool-1-thread-3
Amit job started by thread pool-1-thread-2
Rupani job started by thread pool-1-thread-1
Anil job started by thread pool-1-thread-3
Mukesh job started by thread pool-1-thread-2
  • In the above exmple 3 threads are responsible to execute 6 jobs. So that a single thread can be reuse for multiple jons.
  • While designing web servers and application servers we can use thread pool concept.