The Wayback Machine - https://web.archive.org/web/20170911002335/http://opensource.sys-con.com:80/node/4151910

Welcome!

Open Source Cloud Authors: Elizabeth White, Stackify Blog, Ambuj Kumar, Mehdi Daoudi, Yeshim Deniz

Related Topics: Government Cloud, Java IoT, Open Source Cloud, Containers Expo Blog

Government Cloud: Blog Feed Post

Finally Getting the Most out of the Java Thread Pool | @CloudExpo #JVM #Java #Cloud

Thread pool is a core concept in multithreaded programming that represents a collection of idle threads used to execute tasks

Finally Getting the Most out of the Java Thread Pool
By Eugen Paraschiv

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.

Why Use a Thread Pool?
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 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 which share an unbounded queue; if all threads are active when a new task is submitted, they will wait in 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 2 ms delay, then repeats it at 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 look, 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:

fork/join thread pool

In contrast with this model, the ThreadPoolExecutor uses only one central queue.

One last thing to remember is that the 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 3 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.

This is actually a great way to explore and understand thread pools at runtime, with the help of a solid logging visualization tool such as Prefix.

The core aspect of logging from a thread pool is to make sure the thread name is easily identifiable in the log message; Log4J2 is a great way to do that by making good use of layouts for example.

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 multi-threading 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.

The post Finally Getting the Most out of the Java Thread Pool appeared first on Stackify.

Read the original blog entry...

More Stories By Stackify Blog

Stackify offers the only developers-friendly solution that fully integrates error and log management with application performance monitoring and management. Allowing you to easily isolate issues, identify what needs to be fixed quicker and focus your efforts – Support less, Code more. Stackify provides software developers, operations and support managers with an innovative cloud based solution that gives them DevOps insight and allows them to monitor, detect and resolve application issues before they affect the business to ensure a better end user experience. Start your free trial now stackify.com

@ThingsExpo Stories
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, will prese...
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
The Internet giants are fully embracing AI. All the services they offer to their customers are aimed at drawing a map of the world with the data they get. The AIs from these companies are used to build disruptive approaches that cannot be used by established enterprises, which are threatened by these disruptions. However, most leaders underestimate the effect this will have on their businesses. In his session at 21st Cloud Expo, Rene Buest, Director Market Research & Technology Evangelism at Ara...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Launched in 2016, Cloudistics helps anyone bring the power of the cloud to the data center in an easy-to-use, on- premises cloud platform that automatically provides high performance resources for all types of applications: Docke...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infrastructure throu...
SYS-CON Events announced today that WineSOFT will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Based in Seoul and Irvine, WineSOFT is an innovative software house focusing on internet infrastructure solutions. The venture started as a bootstrap start-up in 2010 by focusing on making the internet faster and more powerful. WineSOFT’s knowledge is based on the expertise of TCP/IP, VPN, SS...
SYS-CON Events announced today that Golden Gate University will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
DevOps at Cloud Expo – being held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real r...
SYS-CON Events announced today that Pulzze Systems will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Pulzze Systems Inc, provides the software product "The Interactor" that uniquely simplifies building IoT, Web and Smart Enterprise Solutions. It is a Silicon Valley startup funded by US government agencies, NSF and DHS to bring innovative solutions to market.
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that SkyScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SkyScale is a world-class provider of cloud-based, ultra-fast multi-GPU hardware platforms for lease to customers desiring the fastest performance available as a service anywhere in the world. SkyScale builds, configures, and manages dedicated systems strategically located in maximum-security...
SYS-CON Events announced today that TMC has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo and Big Data at Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Global buyers rely on TMC’s content-driven marketplaces to make purchase decisions and navigate markets. Learn how we can help you reach your marketing goals.
SYS-CON Events announced today that Grape Up will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...