Why use a recursive task?

The tasks could fork more subtasks themselves . To look at this aspect, let's extend the preceding egrep program to allow a recursive grep—given a directory, the program will recursively find all occurrences of the word in all the files in the directory tree.

We change the previous code suitably, as shown here: 

public class EgrepWord1 {  private final static ForkJoinPool forkJoinPool = new ForkJoinPool();  private static class WordFinder extends RecursiveTask<List<String>> {    final File file;    final String word;    private WordFinder(File file, String word) {      this.file = file;      this.word = word;    }

The task works on two kinds of files: if it is a directory, the task enters the directory and spawns off more subtasks to process ...

Get Concurrent Patterns and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.