Java Executors control rejected tasks

Description

Java Executors control rejected tasks

import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Task implements Runnable {
  private String name;
  public Task(String name) {
    this.name = name;
  }// w w w. j a va2s  .  co m

  @Override
  public void run() {
    System.out.println("Starting:"+ name);
    try {
      Long duration = (long) (Math.random() * 10);
      System.out.println(name+" "+ duration);
      TimeUnit.SECONDS.sleep(duration);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Ending:"+ name);
  }

  public String toString() {
    return name;
  }

}

class RejectedTaskController implements RejectedExecutionHandler {

  @Override
  public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
    System.out.println("The task %s has been rejected:"+ r.toString());
    System.out.println(executor.toString());
    System.out.println("Terminating:"+ executor.isTerminating());
    System.out.println("Terminated:"+ executor.isTerminated());
  }
}

public class Main {
  public static void main(String[] args) {
    // Create the controller for the Rejected tasks
    RejectedTaskController controller = new RejectedTaskController();
    // Create the executor and establish the controller for the Rejected tasks
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    executor.setRejectedExecutionHandler(controller);

    System.out.println("Starting.\n");
    for (int i = 0; i < 3; i++) {
      Task task = new Task("Task" + i);
      executor.submit(task);
    }

    // Shutdown the executor
    System.out.println("Shuting down the Executor.\n");
    executor.shutdown();

    // Send another task
    System.out.println("Sending another Task.\n");
    Task task = new Task("RejectedTask");
    executor.submit(task);

    // The program ends
    System.out.println("End.\n");
  }
}



PreviousNext

Related