RejectedExecutionException

Learn the causes of RejectedExecutionException being thrown.

We'll cover the following

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

Rather than creating individual threads for executing jobs in parallel, we can leverage Java’s executor classes that abstract away thread scheduling and management from the user and leave the user to focus on submitting Runnable or Callable tasks/commands. Some of the classes implementing the Executor and ExecutorService interfaces are as follows:

  • AbstractExecutorService
  • ForkJoinPool
  • ScheduledThreadPoolExecutor
  • ThreadPoolExecutor

The Executor interface defines a method execute while the ExecutorService defines overloaded versions of the submit method. Both these methods throw the runtime exception RejectedExecutionException when implemented by the various executor classes. The RejectedExecutionException exception is thrown when a task can’t be accepted by the executor for execution. Generally there are two scenarios when a task is rejected for execution: The executor service has already been shut down. When the executor service has exhausted resources and can’t take on any more task submissions. For instance in the case of the ThreadPoolExecutor, the RejectedExecutionException is thrown when the executor service uses a queue with a defined maximum capacity and a defined maximum number of threads for the thread pool and both resources have reached capacity.

Example

Consider the program below that attempts to submit a task for execution to a fixed-size thread pool executor, after shutdown() has already been invoked. The executor throws the RejectedExecutionException.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy