Java ForkJoinPool run tasks asynchronously

Description

Java ForkJoinPool run tasks asynchronously


import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

class FolderProcessor extends RecursiveTask<List<String>> {
  private String path;
  
  public FolderProcessor (String path) {
    this.path=path;
  }//  w w  w .  j  ava  2  s  . c o  m
  
  @Override
  protected List<String> compute() {
    List<String> list=new ArrayList<>();
    List<FolderProcessor> tasks=new ArrayList<>();
    
    File file=new File(path);
    File content[] = file.listFiles();
    if (content != null) {
      for (int i = 0; i < content.length; i++) {
        if (content[i].isDirectory()) {
          FolderProcessor task=new FolderProcessor(content[i].getAbsolutePath());
          task.fork();
          tasks.add(task);
        } else {
          if (checkFile(content[i].getName())){
            list.add(content[i].getAbsolutePath());
          }
        }
      }
      System.out.println(file.getAbsolutePath()+" "+tasks.size());
      addResultsFromTasks(list,tasks);
    }
    return list;
  }
  private void addResultsFromTasks(List<String> list,
      List<FolderProcessor> tasks) {
    for (FolderProcessor item: tasks) {
      list.addAll(item.join());
    }
  }
  private boolean checkFile(String name) {
      return true;
  }
}

public class Main {
  public static void main(String[] args) {

    ForkJoinPool pool=new ForkJoinPool();
    
    FolderProcessor java=new FolderProcessor("Java");
    FolderProcessor css=new FolderProcessor("CSS");
    FolderProcessor javascript=new FolderProcessor("Javascript");
    
    pool.execute(java);
    pool.execute(css);
    pool.execute(javascript);
    
    // Write statistics of the pool until the three tasks end
    do {
      System.out.println("Parallelism: "+pool.getParallelism());
      System.out.println("Active Threads: "+pool.getActiveThreadCount());
      System.out.println("Task Count: "+pool.getQueuedTaskCount());
      System.out.println("Steal Count: "+pool.getStealCount());
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    } while ((!java.isDone())||(!css.isDone())||(!javascript.isDone()));
    
    // Shutdown the pool
    pool.shutdown();
    
    // Write the number of results calculate by each task
    List<String> results;
    
    results=java.join();
    System.out.println("Java: %d files found:"+results.size());
    
    results=css.join();
    System.out.println("CSS: %d files found:"+results.size());
    
    results=javascript.join();
    System.out.println("Javascript: %d files found:"+results.size());
  }
}



PreviousNext

Related