Skip to content

Instantly share code, notes, and snippets.

@adyliu
Created December 16, 2014 08:43
Show Gist options
  • Save adyliu/3c642795456da67741c5 to your computer and use it in GitHub Desktop.
Save adyliu/3c642795456da67741c5 to your computer and use it in GitHub Desktop.
a fork join demo
/**
*
*/
package demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;
/**
* a fork join demo
*
* @author adyliu ([email protected])
* @since 2014年12月16日
*/
public class ForkJoinDemo {
final static int SEED = 100;
final static Random r = new Random();
static class Poa {
final long count = r.nextInt(SEED);
}
static class Doa {
List<Poa> poas = Arrays.stream(new int[r.nextInt(SEED)]).mapToObj(t -> new Poa()).collect(Collectors.toList());
long sum() {
return poas.stream().mapToLong(poa -> poa.count).sum();
}
}
static class Trip {
List<Doa> doas = Arrays.stream(new int[r.nextInt(SEED)]).mapToObj(t -> new Doa()).collect(Collectors.toList());
long sum() {
return doas.stream().mapToLong(doa -> doa.sum()).sum();
}
}
static class SumTask extends RecursiveTask<Long> {
Trip trip;
List<Trip> trips = new ArrayList<>();
List<SumTask> tasks = new ArrayList<>();
public SumTask(List<Trip> trips) {
this.trips = trips;
}
public SumTask(Trip trip) {
this.trip = trip;
}
@Override
protected Long compute() {
long sum = 0;
for (Trip t : trips) {
SumTask task = new SumTask(t);
tasks.add(task);
task.fork();
}
if (trip != null) {
sum += trip.sum();
}
for (SumTask task : tasks) {
sum += task.join();
}
return sum;
}
}
public static void main(String[] args) throws Exception {
List<Trip> trips = Arrays.stream(new int[r.nextInt(SEED)]).mapToObj(t -> new Trip()).collect(Collectors.toList());
//
final SumTask sumTask = new SumTask(trips);
final ForkJoinPool forkJoinPool = new ForkJoinPool();
long sum = forkJoinPool.invoke(sumTask);
//
System.out.println(sum);
forkJoinPool.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment