Getting the Most Out of the Java Thread Pool
Dive into the inner workings of thread pooling in Java, the various thread pools at your disposal, and tips on how to make your programs more performant.
Join the DZone community and get the full member experience.
Join For Freethe thread pool is a core concept in multithreaded programming that, simply put, represents a collection of idle threads that can be used to execute tasks.
first, let’s outline a frame of reference for multithreading and why we may need to use a thread pool.
a thread is an execution context that can run a set of instructions within a process – aka a running program. multithreaded programming refers to using threads to execute multiple tasks concurrently. of course, this paradigm is well supported on the jvm.
although this brings several advantages, primarily regarding the performance of a program, multithreaded programming can also have disadvantages – such as increased complexity of the code, concurrency issues, unexpected results, and adding the overhead of thread creation.
in this article, we’re going to take a closer look at how the latter issue can be mitigated by using thread pools in java.
creating and starting a thread can be an expensive process. by repeating this process every time we need to execute a task, we’re incurring a significant performance cost – which is exactly what we were attempting to improve by using threads.
for a better understanding of the cost of creating and starting a thread, let’s see what the jvm actually does behind the scenes:
- it allocates memory for a thread stack that holds a frame for every thread method invocation.
- each frame consists of a local variable array, return value, operand stack, and constant pool.
- some jvms that support native methods also allocate a native stack.
- each thread gets a program counter that tells it what the current instruction executed by the processor is.
- the system creates a native thread corresponding to the java thread.
- descriptors relating to the thread are added to the jvm internal data structures.
- the threads share the heap and method area.
of course, the details of all this will depend on the jmv and the operating system.
in addition, more threads mean more work for the system scheduler to decide which thread gets access to resources next.
a thread pool helps mitigate the issue of performance by reducing the number of threads needed and managing their lifecycle.
essentially, threads are kept in the thread pool until they’re needed, after which they execute the task and return the pool to be reused later. this mechanism is especially helpful in systems that execute a large number of small tasks.
java thread pools
java provides its own implementations of the thread pool pattern, through objects called executors . these can be used through executor interfaces or directly through thread pool implementations – which does allow for finer-grained control.
the java.util.concurrent package contains the following interfaces:
- executor – a simple interface for executing tasks.
- executorservice – a more complex interface which contains additional methods for managing the tasks and the executor itself.
- scheduledexecutorservice – extends executorservice with methods for scheduling the execution of a task.
alongside these interfaces, the package also provides the executors helper class for obtaining executor instances, as well as implementations for these interfaces.
generally, a java thread pool is composed of:
- the pool of worker threads, responsible for managing the threads.
- a thread factory that is responsible for creating new threads.
- a queue of tasks waiting to be executed.
in the following sections, let’s see how the java classes and interfaces that provide support for thread pools work in more detail.
the executors class and executor interface
the executors class contains factory methods for creating different types of thread pools, while executor is the simplest thread pool interface, with a single execute() method.
let’s use these two classes in conjunction with an example that creates a single-thread pool, then uses it to execute a simple statement:
executor executor = executors.newsinglethreadexecutor();
executor.execute(() -> system.out.println("single thread pool test"));
notice how the statement can be written as a lambda expression – which is inferred to be of the runnable type.
the execute() method runs the statement if a worker thread is available or places the runnable task in a queue to wait for a thread to become available.
basically, the executor replaces the explicit creation and management of a thread.
the factory methods in the executors class can create several types of thread pools:
- newsinglethreadexecutor() – a thread pool with only one thread with an unbounded queue, which only executes one task at a time.
- newfixedthreadpool() – a thread pool with a fixed number of threads that share an unbounded queue; if all threads are active when a new task is submitted, they will wait in the queue until a thread becomes available.
- newcachedthreadpool() – a thread pool that creates new threads as they are needed.
- newworkstealingthreadpool() – a thread pool based on a “work-stealing” algorithm, which will be detailed more in a later section.
next, let’s take a look into what additional capabilities the executorservice interface.
the executorservice
one way to create an executorservice is to use the factory methods from the executors class:
executorservice executor = executors.newfixedthreadpool(10);
besides the execute() method, this interface also defines a similar submit() method that can return a future object:
callable<double> callabletask = () -> {
return employeeservice.calculatebonus(employee);
};
future<double> future = executor.submit(callabletask);
// execute other operations
try {
if (future.isdone()) {
double result = future.get();
}
} catch (interruptedexception | executionexception e) {
e.printstacktrace();
}
as you can see in the example above, the future interface can return the result of a task for callable objects, and can also show the status of a task execution.
the executorservice is not automatically destroyed when there are no tasks waiting to be executed, so to shut it down explicitly, you can use the shutdown() or shutdownnow() apis :
executor.shutdown();
the scheduledexecutorservice
this is a subinterface of executorservice – which adds methods for scheduling tasks:
scheduledexecutorservice executor = executors.newscheduledthreadpool(10);
the schedule() method specifies a task to be executed, a delay value and a timeunit for the value:
future<double> future = executor.schedule(callabletask, 2, timeunit.milliseconds);
furthermore, the interface defines two additional methods:
executor.scheduleatfixedrate(
() -> system.out.println("fixed rate scheduled"), 2, 2000, timeunit.milliseconds);
executor.schedulewithfixeddelay(
() -> system.out.println("fixed delay scheduled"), 2, 2000, timeunit.milliseconds);
the scheduleatfixedrate() method executes the task after a 2 ms delay, then repeats it every 2 seconds. similarly, the schedulewithfixeddelay() method starts the first execution after 2 ms, then repeats the task 2 seconds after the previous execution ends.
in the following sections, let’s also go through two implementations of the executorservice interface: threadpoolexecutor and forkjoinpool .
the threadpoolexecutor
this thread pool implementation adds the ability to configure parameters , as well as extensibility hooks. the most convenient way to create a threadpoolexecutor object is by using the executors factory methods:
threadpoolexecutor executor = (threadpoolexecutor) executors.newfixedthreadpool(10);
in this manner, the thread pool is preconfigured for the most common cases. the number of threads can be controlled by setting the parameters:
- corepoolsize and maximumpoolsize – which represent the bounds of the number of threads
- keepalivetime – which determines the time to keep extra threads alive
digging a bit further, here’s how these parameters are used.
if a task is submitted and fewer than corepoolsize threads are in execution, then a new thread is created. the same thing happens if there are more than [ corepoolsize ] but less than [ maximumpoolsize ] threads running, and the task queue is full. if there are more than [ corepoolsize ] threads, which have been idle for longer than [ keepalivetime ], they will be terminated.
in the example above, the newfixedthreadpool() method creates a thread pool with corepoolsize = maximumpoolsize =10, and a keepalivetime of 0 seconds.
if you use the newcachedthreadpool() method instead, this will create a thread pool with a maximumpoolsize of integer.max_value and a keepalivetime of 60 seconds:
threadpoolexecutor cachedpoolexecutor
= (threadpoolexecutor) executors.newcachedthreadpool();
the parameters can also be set through a constructor or through setter methods:
threadpoolexecutor executor = new threadpoolexecutor(
4, 6, 60, timeunit.seconds, new linkedblockingqueue<runnable>()
);
executor.setmaximumpoolsize(8);
a subclass of threadpoolexecutor is the scheduledthreadpoolexecutor class , which implements the scheduledexecutorservice interface. you can create this type of thread pool by using the newscheduledthreadpool() factory method:
scheduledthreadpoolexecutor executor
= (scheduledthreadpoolexecutor) executors.newscheduledthreadpool(5);
this creates a thread pool with a corepoolsize of 5, an unbounded maximumpoolsize , and a keepalivetime of 0 seconds.
the forkjoinpool
another implementation of a thread pool is the forkjoinpool class. this implements the executorservice interface and represents the central component of the fork/join framework introduced in java 7.
the fork/join framework is based on a “work-stealing algorithm” . in simple terms, what this means is that threads that run out of tasks can “steal” work from other busy threads.
a forkjoinpool is well-suited for cases when most tasks create other subtasks or when many small tasks are added to the pool from external clients.
the workflow for using this thread pool typically looks something like this:
- create a forkjointask subclass
- split the tasks into subtasks according to a condition
- invoke the tasks
- join the results of each task
- create an instance of the class and add it to the pool
to create a forkjointask , you can choose one of its more commonly used subclasses, recursiveaction or recursivetask , if you need to return a result.
let’s implement an example of a class that extends recursivetask and calculates the factorial of a number by splitting it into subtasks depending on a threshold value:
public class factorialtask extends recursivetask<biginteger> {
private int start = 1;
private int n;
private static final int threshold = 20;
// standard constructors
@override
protected biginteger compute() {
if ((n - start) >= threshold) {
return forkjointask.invokeall(createsubtasks())
.stream()
.map(forkjointask::join)
.reduce(biginteger.one, biginteger::multiply);
} else {
return calculate(start, n);
}
}
}
the main method that this class needs to implement is the overridden compute() method, which joins the result of each subtask.
the actual splitting is done in the createsubtasks() method:
private collection<factorialtask> createsubtasks() {
list<factorialtask> dividedtasks = new arraylist<>();
int mid = (start + n) / 2;
dividedtasks.add(new factorialtask(start, mid));
dividedtasks.add(new factorialtask(mid + 1, n));
return dividedtasks;
}
finally, the calculate() method contains the multiplication of values in a range:
private biginteger calculate(int start, int n) {
return intstream.rangeclosed(start, n)
.maptoobj(biginteger::valueof)
.reduce(biginteger.one, biginteger::multiply);
}
next, tasks can be added to a thread pool:
forkjoinpool pool = forkjoinpool.commonpool();
biginteger result = pool.invoke(new factorialtask(100));
threadpoolexecutor vs. forkjoinpool
at first glance, it seems that the fork/join framework brings improved performance. however, this may not always be the case depending on the type of problem you need to solve.
when choosing a thread pool, it’s important to also remember there is overhead caused by creating and managing threads and switching execution from one thread to another.
the threadpoolexecutor provides more control over the number of threads and the tasks that are executed by each thread. this makes it more suitable for cases when you have a smaller number of larger tasks that are executed on their own threads.
by comparison, the forkjoinpool is based on threads “stealing” tasks from other threads. because of this, it is best used to speed up work in cases when tasks can be broken up into smaller tasks.
to implement the work-stealing algorithm, the fork/join framework uses two types of queues:
- a central queue for all tasks
- a task queue for each thread
when threads run out of tasks in their own queues, they attempt to take tasks from the other queues. to make the process more efficient, the thread queue uses a deque (double ended queue) data structure, with threads being added at one end and “stolen” from the other end.
here is a good visual representation of this process from the h developer :
in contrast with this model, the threadpoolexecutor uses only one central queue.
one last thing to remember is that choosing a forkjoinpool is only useful if the tasks create subtasks. otherwise, it will function the same as a threadpoolexecutor , but with extra overhead.
tracing thread pool execution
now that we have a good foundational understanding of the java thread pool ecosystem, let’s take a closer look at what happens during the execution of an application that uses a thread pool.
by adding some logging statements in the constructor of factorialtask and the calculate() method, you can follow the invocation sequence:
13:07:33.123 [main] info root - new factorialtask created
13:07:33.123 [main] info root - new factorialtask created
13:07:33.123 [main] info root - new factorialtask created
13:07:33.123 [main] info root - new factorialtask created
13:07:33.123 [forkjoinpool.commonpool-worker-1] info root - new factorialtask created
13:07:33.123 [forkjoinpool.commonpool-worker-1] info root - new factorialtask created
13:07:33.123 [main] info root - new factorialtask created
13:07:33.123 [main] info root - new factorialtask created
13:07:33.123 [main] info root - calculate factorial from 1 to 13
13:07:33.123 [forkjoinpool.commonpool-worker-1] info root - new factorialtask created
13:07:33.123 [forkjoinpool.commonpool-worker-2] info root - new factorialtask created
13:07:33.123 [forkjoinpool.commonpool-worker-1] info root - new factorialtask created
13:07:33.123 [forkjoinpool.commonpool-worker-2] info root - new factorialtask created
13:07:33.123 [forkjoinpool.commonpool-worker-1] info root - calculate factorial from 51 to 63
13:07:33.123 [forkjoinpool.commonpool-worker-2] info root - calculate factorial from 76 to 88
13:07:33.123 [forkjoinpool.commonpool-worker-3] info root - calculate factorial from 64 to 75
13:07:33.163 [forkjoinpool.commonpool-worker-3] info root - new factorialtask created
13:07:33.163 [main] info root - calculate factorial from 14 to 25
13:07:33.163 [forkjoinpool.commonpool-worker-3] info root - new factorialtask created
13:07:33.163 [forkjoinpool.commonpool-worker-2] info root - calculate factorial from 89 to 100
13:07:33.163 [forkjoinpool.commonpool-worker-3] info root - calculate factorial from 26 to 38
13:07:33.163 [forkjoinpool.commonpool-worker-3] info root - calculate factorial from 39 to 50
here you can see there are several tasks created, but only three worker threads – so these get picked up by the available threads in the pool.
also notice how the objects themselves are actually created in the main thread before being passed to the pool for execution.
potential risks of using a thread pool
although thread pools provide significant advantages, you can also encounter several problems while using one, such as:
- using a thread pool that is too large or too small – if the thread pool contains too many threads, this can significantly affect the performance of the application; on the other hand, a thread pool that is too small may not bring the performance gain that you would expect
- deadlock can happen just like in any other multithreading situation; for example, a task may be waiting for another task to complete with no available threads for this latter one to execute; that’s why it’s usually a good idea to avoid dependencies between tasks
- queuing a very long task – to avoid blocking a thread for too long, you can specify a maximum wait time after which the task is rejected or re-added to the queue
to mitigate these risks, you have to choose the thread pool type and parameters carefully according to the tasks that they will handle. stress-testing your system is also well worth it to get some real-world data of how your thread pool behaves under load.
conclusion
thread pools provide a significant advantage by, simply put, separating the execution of tasks from the creation and management of threads. additionally, when used right, they can greatly improve the performance of your application.
and, the great thing about the java ecosystem is that you have access to some of the most mature and battle-tested implementations of thread-pools out there if you learn to leverage them properly and take full advantage of them.
Published at DZone with permission of Eugen Paraschiv, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments