Thread Pools
CSCI 201
Principles of Software Development
Jeffrey Miller, Ph.D.
[Link]@[Link]
Outline
Thread Pools
USC CSCI 201L
Thread Pool Overview
If you need to create a lot of threads, it may not be the most
efficient to create them by instantiating them all as threads
and starting them
There may be performance issues, such as limiting throughput, if
there are too many threads
A thread pool helps to manage the number of threads
executing concurrently
If a thread in a thread pool completes execution, it can be reused
instead of needing to create another thread
If a thread terminates due to failing, another thread will be created to
replace it
The execute method will execute the thread at some time
in the future, determined by the Executor
USC CSCI 201L 3/6
Thread Management
Thread pools also give us more information about the
state of threads
We are able to find out if all of the threads that were
invoked have completed
[Link]()
We can also make sure no additional threads can be
created by terminating the pool (though existing threads
will still be able to complete)
[Link]()
[Link]() will kill all currently
executing threads in the pool
USC CSCI 201L 4/6
Executors Class
The Executors class provides factory and utility methods for
executing threads
newCachedThreadPool()
Creates a thread pool that creates new threads as needed and reuses
previously constructed threads when they are available
newFixedThreadPool(int numThreads)
Creates a thread pool that reuses a fixed number of threads. At any
point, a maximum of numThreads will be alive
newScheduledThreadPool(int corePoolSize)
Creates a thread pool that can schedule commands to run after a
given delay or to execute periodically
newSingleThreadExecutor()
Creates an Executor that uses a single worker thread
USC CSCI 201L 5/6
Thread Pool Example
1 import [Link];
2 import [Link];
3
4 public class Test {
5 public static void main(String[] args) {
6 [Link]("First line");
7 ExecutorService executor = [Link](3);
8 [Link](new TestThread('a'));
9 [Link](new TestThread('b'));
10 [Link](new TestThread('c'));
11 [Link](); // threads will still complete, [Link]() otherwise
12 while (![Link]()) {
13 [Link]();
14 }
15 [Link]("Last line");
16 }
17 }
18 class TestThread extends Thread {
19 private char c;
20 public TestThread(char c) {
21 this.c = c;
22 }
23 public void run() {
24 for (int i=0; i < 20; i++) {
25 [Link](i + "" + c + " ");
26 }
27 [Link]("");
28 }
29 }
USC CSCI 201L 6/6