In this Project we have make two classes named:-
1. CustomRecursiveTask.java
2. JoinForkDemo.java
2. JoinForkDemo.java
Program:-
CustomRecursiveTask.java:-
package com.gpm.tcp_client_server;
import java.util.concurrent.RecursiveTask;
import java.util.ArrayList;
import java.util.List;
public class CustomRecursiveTask extends RecursiveTask<Integer>
{
ArrayList<Integer> task;
int threshold = 2;
public CustomRecursiveTask(ArrayList<Integer> task)
{
this.task = task;
System.out.println();
System.out.println("Task Array> ");
for(Integer i : task)
{
System.out.print(i+" ");
}
System.out.println();
}
@Override
protected Integer compute()
{
int result = 0;
if(task.size() > threshold)
{
//Divide current task into subtask
List<CustomRecursiveTask>taskList = new
ArrayList<CustomRecursiveTask>();
taskList.addAll(CreateSubtask());
for(CustomRecursiveTask subtask : taskList)
{
subtask.fork();
}
for(CustomRecursiveTask subtask : taskList)
{
result += subtask.join();
}
}
else
{
//process task
result=Process();
}
System.out.println("Addition of current task >" +result);
return result;
}
private int Process()
{
int result = 0;
for(int i=0 ; i<this.task.size() ;i++)
{
result = result + this.task.get(i);
}
return result;
}
private List<CustomRecursiveTask> CreateSubtask()
{
int listSize = this.task.size();
List<CustomRecursiveTask> subtask = new
ArrayList<CustomRecursiveTask>(2);
ArrayList<Integer>FirstArray = new ArrayList<Integer>();
FirstArray = MakeArrayIntegerList(this.task,0,listSize/2-
1);
ArrayList<Integer>SecondArray = new ArrayList<Integer>();
SecondArray =
MakeArrayIntegerList(this.task,listSize/2,listSize-1);
subtask.add(new CustomRecursiveTask(FirstArray));
subtask.add(new CustomRecursiveTask(SecondArray));
return subtask;
}
private ArrayList<Integer>
MakeArrayIntegerList(ArrayList<Integer>list , int startIndex, int
lastIndex)
{
ArrayList<Integer>newList = new ArrayList<Integer>();
for(int i= startIndex ; i<=lastIndex; i++)
{
newList.add(list.get(i));
}
return newList;
}
}
JoinForkDemo.java:-
package com.gpm.tcp_client_server;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.ForkJoinPool;
public class JoinForkDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int size;
int result;
System.out.println("Enter Number of elements> ");
size = sc.nextInt();
ArrayList<Integer> elements = new ArrayList<Integer>(size);
System.out.println("Enter Elements > ");
for(int i=0 ;i<size;i++)
{
elements.add(sc.nextInt());
}
ForkJoinPool pool = new ForkJoinPool();
CustomRecursiveTask customRecursiveTask = new
CustomRecursiveTask(elements);
result = pool.invoke(customRecursiveTask);
System.out.println("Addition > "+result);
}
}
Output:-