Java Thread Pool – ExecutorService

Java Thread Pool is a performance solution for scaling system, so JavaSampleApproach will guide you how to work with Java Thread Pool by ExecutorService and Executors.

I. Concepts
1. ExecutorService & Executors

java.util.concurrent.ExecutorService provides methods to manage termination and methods to produce a Future for tracking progress of tasks.

java.util.concurrent.Executors class provides factory methods for the executor services.

2. Methods

public static ExecutorService newFixedThreadPool(int nThreads): creates a thread pool for reusing a fixed number of threads . At any point if having any tasked are submitted when all threads are active, they will wait until a thread is available.

public static ExecutorService newSingleThreadExecutor(): creates an Executor that uses a single worker thread. Tasks are guaranteed to execute sequentially, and no more than one task will be active at a specific time.

Note:
– Difference between newFixedThreadPool(1) & newSingleThreadExecutor(): Executor of newSingleThreadExecutor() factory method guaranteed not to be reconfigurable at runtime.

– If a thread terminates(both: newFixedThreadPool() & newSingleThreadExecutor()) due to a failure during execution prior to shutdown, a new one will created for executing subsequent tasks.

void java.util.concurrent.Executor.execute(Runnable command): executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.

void java.util.concurrent.ExecutorService.shutdown(): setup a shutdown right after all submitted tasks are executed, and not accepted any new task.

boolean java.util.concurrent.ExecutorService.isTerminated(): returns true if all tasks have completed after shut down.
Note: isTerminated is always false unless either shutdown or shutdownNow was called first.

II. Practice
1. Create WorkerThread

2. Sample with newFixedThreadPool

Sourcecode:

Outuput:

3. Sample with newSingleThreadExecutor

Sourcecode:

Output:

4. Source code

Java ThreadPool

By JavaSampleApproach | December 21, 2016.

Last updated on June 4, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*