Java ForkJoinPool create Fork/Join pool

Description

Java ForkJoinPool create Fork/Join pool

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

class Book {
  private String name;
  private double price;

  public String getName() {
    return name;//from w  w  w .j  a  v a 2s.  c om
  }

  public void setName(String name) {
    this.name = name;
  }

  public double getPrice() {
    return price;
  }

  public void setPrice(double price) {
    this.price = price;
  }

}

class Task extends RecursiveAction {
  private List<Book> bookList;

  private int first;
  private int last;

  private double increment;

  public Task(List<Book> products, int first, int last, double increment) {
    this.bookList = products;
    this.first = first;
    this.last = last;
    this.increment = increment;
  }

  @Override
  protected void compute() {
    if (last - first < 10) {
      updatePrices();
    } else {
      int middle = (last + first) / 2;
      System.out.println("Pending tasks: "+ getQueuedTaskCount());
      Task t1 = new Task(bookList, first, middle + 1, increment);
      Task t2 = new Task(bookList, middle + 1, last, increment);
      invokeAll(t1, t2);
    }
  }

  private void updatePrices() {
    for (int i = first; i < last; i++) {
      Book product = bookList.get(i);
      product.setPrice(product.getPrice() * (1 + increment));
    }
  }
}

public class Main {
  public static List<Book> generate(int size) {
    List<Book> ret = new ArrayList<Book>();

    for (int i = 0; i < size; i++) {
      Book product = new Book();
      product.setName("Java " + i);
      product.setPrice(10);
      ret.add(product);
    }

    return ret;
  }
  public static void main(String[] args) {
    List<Book> bookList = generate(10000);

    Task task = new Task(bookList, 0, bookList.size(), 0.20);
    ForkJoinPool pool = new ForkJoinPool();
    pool.execute(task);
    do {
      System.out.println("Thread Count: "+ pool.getActiveThreadCount());
      System.out.println("Thread Steal: "+ pool.getStealCount());
      System.out.println("Paralelism: "+ pool.getParallelism());
      try {
        TimeUnit.MILLISECONDS.sleep(5);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    } while (!task.isDone());

    pool.shutdown();

    if (task.isCompletedNormally()) {
      System.out.println("The process has completed normally.");
    }

    for (int i = 0; i < bookList.size(); i++) {
      Book book = bookList.get(i);
      if (book.getPrice() != 12) {
        System.out.println("Product: "+ book.getName()+" "+ book.getPrice());
      }
    }
    System.out.println("End of the program.");
  }
}



PreviousNext

Related