Divide and Conquer technique is often used to solve many problems. The Problem is divided on the basis of size and that small size problem is solved and then merged accordingly to get the required solution. In a multi threaded environment using the feature of cuncurrency is the best option to get the better result from performance point of view.
Java 7 provides Fork/Join Framework for solving such kind of problem using threads. The best part of this framework like the executor framework it manages the creation and management of backends threads which actually executes your task. The framework also utilise the work stealing algorithm to improve performance this framework. The framework is designed in such a way that it's best suited for solving problem which requires the problem to divided into smaller tasks using divide and conquer technique.
Using ForkJoinPool and RecursiveTask class For Implementing Solution for finding sum of first 1000 natural number using divide and conquer approach
package read.java.thread.fork_joinframework; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; import java.util.concurrent.TimeUnit; class SumOfTen extends RecursiveTask{ /** * */ private static final long serialVersionUID = 1L; int start; int end; public SumOfTen(int start,int end){ this.start=start; this.end=end; } @Override protected Integer compute() { // TODO Auto-generated method stub if(end - start > 10){ int mid = (start + end) / 2; SumOfTen task1=new SumOfTen(start, mid); SumOfTen task2=new SumOfTen(mid+1, end); invokeAll(task1,task2); int sum=0; try{ sum = task1.get() + task2.get(); }catch(Exception exp){ exp.printStackTrace(); } return sum; }else{ return sum(start,end); } } private int sum(int start,int end){ int sum=0; for(int i=start ; i <= end ; i++){ sum+=i; } return sum; } } public class SumOfThousands { /** * @param args * @throws ExecutionException * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException, ExecutionException { // TODO Auto-generated method stub SumOfTen task=new SumOfTen(0,20); ForkJoinPool pool=new ForkJoinPool(); pool.execute(task); do { System.out.printf("******************************************\n"); System.out.printf("Main: Parallelism: %d\n",pool.getParallelism()); System.out.printf("Main: Active Threads: %d\n",pool.getActiveThreadCount()); System.out.printf("Main: Task Count: %d\n",pool.getQueuedTaskCount()); System.out.printf("Main: Steal Count: %d\n",pool.getStealCount()); System.out.printf("******************************************\n"); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } while (!task.isDone()); System.out.println(task.get()); } }
No comments:
Post a Comment