How to use fixed size thread pool Executor in Java? Example Tutorial

We are again with new article that is on using fixed size thread pool executor in Java. The main aim of this article is to give you idea about how to declare string in java and about different ways of declaring. So our viewer will have great knowledge after reading this. If you don't know, a FixedSizeThreadPool is a type of Java Executor that uses a fixed number of threads to carry out tasks. When you have a small number of tasks to complete and want to manage the number of threads that can be used to complete those tasks, this kind of executor is helpful.


Example:

Here is an illustration of how to use a Java FixedSizeThreadPool:

import java.util.concurrent.Executor;

import java.util.concurrent.Executors;


public class FixedSizeThreadPoolExample {

public static void main(String[] args) {

// Create a fixed size thread pool with 5 threads

Executor executor = Executors.newFixedThreadPool(5);



// Submit 10 tasks to the executor

for (int i = 0; i < 10; i++) {

executor.execute(() -> {

System.out.println("Running task on thread: " + Thread.currentThread().getName());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

});

}

}

}



In this example, a fixed size thread pool with 5 threads is created using the Executors.newFixedThreadPool(5) method. The execute method is then used to send 10 tasks to the executor. Each task does nothing more than print a message and wait a second. 

You will see that only 5 tasks are running simultaneously when this code is executed because the FixedSizeThreadPool can only support a maximum of 5 threads. 

How to use fixed size thread pool Executor in Java? Example Tutorial



Once a thread is available, the remaining tasks will be carried out one at a time. It's crucial to remember that FixedSizeThreadPools have a queue where tasks waiting to be executed are kept. The execute method will remain inactive until a thread becomes available or the task is added to the queue if all threads are active and the queue is full. 

The newFixedThreadPool method allows you to specify the queue size as an additional argument. Alternatively, you can use a SynchronousQueue to create a queue with no capacity, which will cause the execute method to immediately time out if all threads are busy.
Shutdown the FixedSizeThreadPool:

Additionally, it's crucial to properly terminate the FixedSizeThreadPool after you're done using it. To accomplish this, use the Executor interface's shutdown method as follows:

import java.util.concurrent.Executor;

import java.util.concurrent.Executors;


public class FixedSizeThreadPoolExample {

public static void main(String[] args) {

// Create a fixed size thread pool with 5 threads

Executor executor = Executors.newFixedThreadPool(5);



// Submit 10 tasks to the executor

for (int i = 0; i < 10; i++) {

executor.execute(() -> {

System.out.println("Running task on thread: " + Thread.currentThread().getName());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

});

}



// Shut down the executor

executor.shutdown();

}

}


The FixedSizeThreadPool receives a signal from the shutdown method that no new tasks will be submitted, and the pool will stop accepting them. The tasks already running in the queue will keep running until they are all finished, and then the FixedSizeThreadPool will shut down. 

Additionally, you can immediately terminate the FixedSizeThreadPool by calling the shutdownNow method. This approach will stop all tasks that are currently running and cancel all tasks that are waiting in the queue.

Finally, to wait for the FixedSizeThreadPool to complete running all tasks, you can use the awaitTermination method from the ExecutorService interface. This method stays in the blocked state until either the timeout expires, the shutdown request times out, or the current thread is interrupted, whichever comes first.


Here is an illustration of the use of await termination:

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;


public class FixedSizeThreadPoolExample {

public static void main(String[] args) {

// Create a fixed size thread pool with 5 threads

ExecutorService executor = Executors.newFixedThreadPool(5);



// Submit 10 tasks to the executor

for (int i = 0; i < 10; i++) {

executor.execute(() -> {

System.out.println("Running task on thread: " + Thread.currentThread().getName());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

});

}



// Shut down the executor

executor.shutdown();



try {

// Wait for all tasks to complete, or timeout after 10 seconds

if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {

System.out.println("Timed out waiting for tasks to complete");

}

} catch (InterruptedException e) {

System.out.println("Interrupted while waiting for tasks to complete");Executor

}

}

CachedThreadPool:

The FixedSizeThreadPool is suitable for use cases where you need to restrict the number of concurrent tasks to a specific number, it is important to note. However, you might want to think about using a different kind of for other use cases.


Example:
You might want to use a CachedThreadPool, for instance, if you have a lot of tasks to complete but the exact number is variable and subject to change. In comparison to creating a fixed number of threads, the CachedThreadPool dynamically increases and decreases the number of threads as necessary.

Here's an example of how to create and use a CachedThreadPool:

import java.util.concurrent.Executor;

import java.util.concurrent.Executors;


public class CachedThreadPoolExample {

public static void main(String[] args) {

// Create a cached thread pool

Executor executor = Executors.newCachedThreadPool();



// Submit 10 tasks to the executor

for (int i = 0; i < 10; i++) {

executor.execute(() -> {

System.out.println("Running task on thread: " + Thread.currentThread().getName());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

});

}



// The CachedThreadPool will shut down automatically when the program exits, so there's no need to shut down the executor.

}

}


Conclusion:
In conclusion, the FixedSizeThreadPool is a strong Java tool for running a fixed number of tasks concurrently. To ensure that your programs function properly and efficiently, it's crucial to understand how to create, use, and shut down a FixedSizeThreadPool.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.