Java ForkJoinPool monitor

Description

Java ForkJoinPool monitor


import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

class Task extends RecursiveAction {
  private int array[];
  private int start;
  private int end;

  public Task(int array[], int start, int end) {
    this.array = array;
    this.start = start;
    this.end = end;
  }//from   w ww.  j a va  2s  . c o m

  @Override
  protected void compute() {
    if (end - start > 100) {
      int mid = (start + end) / 2;
      Task task1 = new Task(array, start, mid);
      Task task2 = new Task(array, mid, end);
      task1.fork();
      task2.fork();
      task1.join();
      task2.join();
    } else {
      for (int i = start; i < end; i++) {
        array[i]++;

        try {
          TimeUnit.MILLISECONDS.sleep(5);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    ForkJoinPool pool = new ForkJoinPool();
    int array[] = new int[10000];
    Task task1 = new Task(array, 0, array.length);
    pool.execute(task1);
    while (!task1.isDone()) {
      System.out.printf("Fork/Join Pool: Parallelism: %d\n", pool.getParallelism());
      System.out.printf("Fork/Join Pool: Pool Size: %d\n", pool.getPoolSize());
      System.out.printf("Fork/Join Pool: Active Thread Count: %d\n", pool.getActiveThreadCount());
      System.out.printf("Fork/Join Pool: Running Thread Count: %d\n", pool.getRunningThreadCount());
      System.out.printf("Fork/Join Pool: Queued Submission: %d\n", pool.getQueuedSubmissionCount());
      System.out.printf("Fork/Join Pool: Queued Tasks: %d\n", pool.getQueuedTaskCount());
      System.out.printf("Fork/Join Pool: Queued Submissions: %s\n", pool.hasQueuedSubmissions());
      System.out.printf("Fork/Join Pool: Steal Count: %d\n", pool.getStealCount());
      System.out.printf("Fork/Join Pool: Terminated : %s\n", pool.isTerminated());

      TimeUnit.SECONDS.sleep(1);
    }
    pool.shutdown();
    pool.awaitTermination(1, TimeUnit.DAYS);
    System.out.printf("Fork/Join Pool: Parallelism: %d\n", pool.getParallelism());
    System.out.printf("Fork/Join Pool: Pool Size: %d\n", pool.getPoolSize());
    System.out.printf("Fork/Join Pool: Active Thread Count: %d\n", pool.getActiveThreadCount());
    System.out.printf("Fork/Join Pool: Running Thread Count: %d\n", pool.getRunningThreadCount());
    System.out.printf("Fork/Join Pool: Queued Submission: %d\n", pool.getQueuedSubmissionCount());
    System.out.printf("Fork/Join Pool: Queued Tasks: %d\n", pool.getQueuedTaskCount());
    System.out.printf("Fork/Join Pool: Queued Submissions: %s\n", pool.hasQueuedSubmissions());
    System.out.printf("Fork/Join Pool: Steal Count: %d\n", pool.getStealCount());
    System.out.printf("Fork/Join Pool: Terminated : %s\n", pool.isTerminated());
  }

}



PreviousNext

Related