Replicated Workers using ExecutorService in Java Threads
The Replicated Workers model in Java is a concurrency design pattern where multiple worker threads (or tasks) perform the same operation in parallel on different data. This model is particularly useful for scenarios where a large task can be divided into smaller, independent subtasks.
In Java, this model can be implemented using the ExecutorService framework, which simplifies the management of worker threads.
In this example, each worker will perform a real calculation, such as computing the sum of the first N integers. We'll have multiple worker threads, each calculating the sum for different values of N.
- SumCalculator.java
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class SumCalculator { static class Worker implements Runnable { private final int n; Worker(int n) { this.n = n; } @Override public void run() { int sum = calculateSum(n); System.out.println("Sum of first " + n + " integers: " + sum + " (Calculated by " + Thread.currentThread().getName() + ")"); } private int calculateSum(int n) { return n * (n + 1) / 2; // Formula for sum of first n integers } } public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(4); // 4 worker threads // Submitting tasks with different values of 'n' for (int i = 1; i <= 8; i++) { executor.submit(new Worker(i * 10)); } executor.shutdown(); executor.awaitTermination(1, TimeUnit.MINUTES); System.out.println("All tasks completed."); } }
Worker Class: Each worker is tasked with calculating the sum of the first n integers. The value of n is passed to the worker at the time of its creation. The calculateSum method uses the formula n * (n + 1) / 2 to compute the sum efficiently.
Submitting Tasks: The main method creates and submits eight tasks to the ExecutorService. Each task is given a different value of n (multiples of 10 in this case).
Concurrent Execution: The executor service manages four threads, and each thread processes the tasks submitted to it. This setup allows for concurrent execution of the sum calculations.
Practical Outcome: Each thread is performing a meaningful computation, which showcases a practical use of the replicated workers model.
This implementation demonstrates how the replicated workers model can be used for parallel computation tasks, allowing for efficient processing of independent, computationally intensive tasks.