Introduction
The newFixedThreadPool
method in the Executors
class creates a thread pool with a fixed number of threads. This type of thread pool is suitable for scenarios where you want to limit the number of concurrent threads running in your application to a specific number. This helps in managing system resources more effectively.
Table of Contents
- Overview of newFixedThreadPool Method
- Creating a Fixed Thread Pool
- Submitting Tasks to Fixed Thread Pool
- Example: Using newFixedThreadPool
- Shutting Down the Thread Pool
- Conclusion
1. Overview of newFixedThreadPool Method
The newFixedThreadPool
method creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads
threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.
Syntax:
public static ExecutorService newFixedThreadPool(int nThreads)
nThreads
: The number of threads in the pool.
2. Creating a Fixed Thread Pool
To create a fixed thread pool, use the newFixedThreadPool
method with the desired number of threads.
Example:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPoolExample {
public static void main(String[] args) {
// Creating a fixed thread pool with 3 threads
ExecutorService executorService = Executors.newFixedThreadPool(3);
// Your tasks go here
executorService.shutdown();
}
}
3. Submitting Tasks to Fixed Thread Pool
Tasks can be submitted to the fixed thread pool using the submit
or execute
method.
Example:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPoolTaskExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
// Submit tasks to the executor service
for (int i = 1; i <= 5; i++) {
final int taskId = i;
executorService.submit(() -> {
System.out.println("Task " + taskId + " executed by " + Thread.currentThread().getName());
try {
Thread.sleep(2000); // Simulate a long-running task
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
}
}
Output:
Task 1 executed by pool-1-thread-1
Task 2 executed by pool-1-thread-2
Task 3 executed by pool-1-thread-3
Task 4 executed by pool-1-thread-1
Task 5 executed by pool-1-thread-2
4. Example: Using newFixedThreadPool
Let's create a complete example that demonstrates how to create a fixed thread pool, submit tasks, and shut it down.
Example:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Task implements Runnable {
private final String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Task " + name + " is being executed by " + Thread.currentThread().getName());
try {
Thread.sleep(2000); // Simulate long-running task
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class FixedThreadPoolDemo {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 5; i++) {
Task task = new Task("Task " + i);
executorService.submit(task);
}
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
System.out.println("All tasks are finished.");
}
}
Output:
Task Task 1 is being executed by pool-1-thread-1
Task Task 2 is being executed by pool-1-thread-2
Task Task 3 is being executed by pool-1-thread-3
Task Task 4 is being executed by pool-1-thread-1
Task Task 5 is being executed by pool-1-thread-2
All tasks are finished.
Explanation:
- The
Task
class implements theRunnable
interface and represents a task that prints its name and the name of the thread executing it. - The
FixedThreadPoolDemo
class creates a fixed thread pool using thenewFixedThreadPool
method with 3 threads. - Five tasks are submitted to the executor service.
- Each task prints its name and the name of the thread executing it.
- The executor service is shut down gracefully, waiting for up to 60 seconds for tasks to complete.
5. Shutting Down the Thread Pool
It's important to properly shut down the ExecutorService
to release resources. You can shut it down gracefully or forcefully.
Graceful Shutdown:
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
Forceful Shutdown:
executorService.shutdownNow();
6. Conclusion
The newFixedThreadPool
method in the Executors
class provides a convenient way to create a thread pool with a fixed number of threads. This type of thread pool is suitable for scenarios where you want to limit the number of concurrent threads running in your application. By using newFixedThreadPool
, you can efficiently manage and execute tasks in your applications.
Happy coding!
Comments
Post a Comment
Leave Comment