A thread pool is a set of worker threads that minimize creation overload by keeping them always available.
It's advisable when there is a massive use of threads for short tasks like in a web server. An other advantage is that the server that receives more request it can handle doesn't stop responding, but will keep answerring although with a delay (that's termed "degrade gracefully").
The classes/interfaces normally used for the implementation are:
Callable (interface): used for the implementation of a task to be executed by the thread.
ExecutorService (interface): used to control the execution of a thread by starting and stopping it or by producing future objects.
Future: represents a result of a thread in the future and is returned by an executor service since a thread can take considerable time to execute.
Executors: factory method to produce objects of type ExecutorService, Callable etc.
Let's see an example of how it works:
import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Class to demonstrate a thread pool * @author Davis Fiore * */ public class App { // Number of threads in the thread pool private static final int NUM_THREADS = 8; /** * Class representing the task to be executed in a thread */ static class Calculator implements Callable<Integer> { private String strVal; /** * Constructor to initialize the object with a number on * which to execute the sum of digits * @param val Number for the sum of digits */ public Calculator(int val) { strVal = String.valueOf(val); } /** * Calculate the sum of every single digit of a number * @return Sum * @throws Exception */ @Override public Integer call() throws Exception { int sum = 0; for (int i=0; i < strVal.length(); i++) sum += Character.digit(strVal.charAt(i), 10); return sum; } } /** * Main method to create a thread pool * @param args * @throws InterruptedException * @throws ExecutionException */ public static void main(String[] args) throws InterruptedException, ExecutionException { // Initialization List<Future<Integer>> results = new ArrayList<>(); Random rnd = new Random(); // Create a thread pool ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS); // Run the threads and create a list of future objects for (int i=0; i < NUM_THREADS; i++) { Callable<Integer> task = new Calculator(rnd.nextInt(1000)); Future<Integer> futureObj = executorService.submit(task); results.add(futureObj); } // Retrieve the results from the list of future objects for (Future<Integer> result : results) { System.out.println(result.get()); } // Terminate the thread pool executorService.shutdown(); } }
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.