How to use ForkJoinPool in Java
Many of you have gone through google to find out on how to use ForkJoinPool for many use cases. But itās hard to find the use case for a DB query. Hereās the simple example on how to use it.
Create a Recursive Task class like the following.
public class MongoQueryForkJoinTask<T> extends RecursiveTask<List<T>> {
Ā Ā private final int pageSize; Ā Ā private int pageIndex; Ā Ā private final Long totalCount; Ā Ā private final Query query; Ā Ā private final MongoTemplate mongoTemplate; Ā Ā private final Class clazz;
Ā Ā private static final Logger LOG = Logger.getLogger(MongoQueryForkJoinTask.class);
Ā Ā public MongoQueryForkJoinTask(int pageSize, int pageIndex, Long totalCount, Query query, MongoTemplate mongoTemplate, Class clazz) { Ā Ā Ā Ā this.pageSize = pageSize; Ā Ā Ā Ā this.pageIndex = pageIndex; Ā Ā Ā Ā this.totalCount = totalCount; Ā Ā Ā Ā this.query = query; Ā Ā Ā Ā this.mongoTemplate = mongoTemplate; Ā Ā Ā Ā this.clazz = clazz; Ā Ā }
Ā Ā @Override Ā Ā protected List<T> compute() { Ā Ā Ā Ā if(totalCount <= pageSize ){ Ā Ā Ā Ā Ā Ā LOG.info("Fetching records for Class ["+clazz.getSimpleName()+"] with pageSize ["+pageSize+"] and pageIndex ["+pageIndex+"], totalCount ["+totalCount+"]"); Ā Ā Ā Ā Ā Ā Pageable pageRequest = new PageRequest(pageIndex, pageSize); Ā Ā Ā Ā Ā Ā query.with(pageRequest); Ā Ā Ā Ā Ā Ā return mongoTemplate.find(query, clazz); Ā Ā Ā Ā } Ā Ā Ā Ā List<T> returnList Ā = new ArrayList<>(); Ā Ā Ā Ā LOG.info("Executing all the tasks..."); Ā Ā Ā Ā for (int i=0;i<pageIndex;i++){ Ā Ā Ā Ā Ā Ā final MongoQueryForkJoinTask<T> task = new MongoQueryForkJoinTask<>(pageSize, i, Long.valueOf(pageSize), query, Ā mongoTemplate, clazz); Ā Ā Ā Ā Ā Ā task.fork(); Ā Ā Ā Ā Ā Ā returnList.addAll(task.join()); Ā Ā Ā Ā } Ā Ā Ā Ā return returnList; Ā Ā } }
And use the same task to invoke via ForkJoinPool.
pool.invoke(new MongoQueryForkJoinTask<Employee>(1000, 10000, count, q, mongoTemplate, Employee.class));
Where q is the Mongo Query that we construct as per our requirements.
If we donāt bother about the pagination and all those stuff, this works good else we loose the parallelism as we did here. We are just forking it and immediately we are joining it.

















