Search code examples
javamultithreadingexceptionpool

How can I get a RejectedExecutionException


Anybody able to provide me with an example of getting a RejectedExecutionException Possibly a real life example. Thanks in advance.


Solution

  • Anybody able to provide me with an example of getting a RejectedExecutionException Possibly a real life example.

    Sure. The following code submits 2 jobs into a thread-pool with only 1 thread running. It uses a SynchronousQueue which means that no jobs will be stored in the job queue.

    Since each job takes a while to run, the 2nd execute fills the queue and throws a RejectedExecutionException.

    // create a 1 thread pool with no buffer for the runnable jobs
    ExecutorService threadPool =
        new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
            new SynchronousQueue<Runnable>());
    // submit 2 jobs that take a while to run
    /// this job takes the only thread
    threadPool.execute(new SleepRunnable());
    // this tries to put the job into the queue, throws RejectedExecutionException
    threadPool.execute(new SleepRunnable());
    
    public class SleepRunnable implements Runnable {
        public void run() {
            try {
                // this just sleeps for a while which pauses the thread
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
    }
    

    This is happening by design because the queue is full and all of the threads are busy. If you want to avoid this problem then you should create a larger queue to store more jobs when all of the worker threads are busy, increase the number of threads working on the jobs (although you can only increase this so far), or block the code that is submitting the jobs to the thread-pool. See: How to implement blocking thread pool executor?