Executor and ExecutorService are the utility classes present starting from JDK 1.5 for executing a java process/block parallely in a controlled manner.
Executor – Executor is used for creates a thread pool to for fixed number, using the method newFixedThreadPool.
e.g., We have a 2 dimensional array where each row needs to be processed or set to particular String.
We are instantiating the ThreadPool by 2 or 3 by using the ExecutorService.
1 |
ExecutorService executor = Executors.newFixedThreadPool(3); |
Each Thread will execute the run method, which will process the corresponding row of the 2D array.
Below statement, initiates an orderly shutdown in which previously submitted tasks are executed, and no new tasks.Invocation has no additional effect if already shut down.
1 |
executor.shutdown(); |
Make the executor wait for Maximum of 10 seconds, if all threads are not processed, give an interruption.
1 |
executor.awaitTermination(10, TimeUnit.SECONDS); |
The below program compares the time spent on the 2D array processing via Executor and normal for loop.
In the below example, for approximately 200 iterations, the time spent in milliseconds doesn’t make any difference.
However for greater than 200, the time saved by Executor via parallel processing makes significant difference, since multiple threads
Since multiple threads are used, Java Executors are faster and effective the for loop for larger sets of iterations., considering memory of the heap.
Example Below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package my.test.learning; import java.util.concurrent.*; public class ProgramTest implements Runnable { static int[][] xyFrame = new int[1000][10000]; int index=0; public ProgramTest(int index){ this.index = index; } <strong>public static void main(String[] args) throws InterruptedException {</strong> long startTime = System.currentTimeMillis(); ExecutorService executor = Executors.newFixedThreadPool(3); for (int i = 0; i < xyFrame.length; i+=1) { ProgramTest pgmTest = new ProgramTest(i); executor.execute(pgmTest); } executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); System.out.println("Total Time in Parallel: " + ((System.currentTimeMillis()- startTime)) + " milliseconds"); startTime = System.currentTimeMillis(); for(int i=0;i<xyFrame.length;i++) { for(int j=0;j<xyFrame[0].length;j++) { ProgramTest pgmTest = new ProgramTest(i); pgmTest.myExecute(); } } System.out.println("Total Time in Normal For Loop: " + ((System.currentTimeMillis()-startTime)) + "milliseconds"); <strong> }</strong> public void myExecute() { for(int i=0;i<xyFrame[0].length;i++) { xyFrame[this.index][i] = 1; // Do Any operation, Here wer just there } } @Override public void run() { myExecute(); } } |
Results:
1 2 |
Total Time in Parallel: 12 milliseconds Total Time in Normal For Loop: 175826 milliseconds |