4

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

Rollerball
  • 11,792
  • 22
  • 89
  • 148

3 Answers3

4

Sending tasks to an executor after calling shutdown( on it will throw this exception.

In addition, if the executor uses a bounded blocking queue if the queue is full submitting the task will not block but will fail-fast with the exception.

nanofarad
  • 38,481
  • 4
  • 83
  • 110
4

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;
        }
    }
}
Gray
  • 112,334
  • 22
  • 281
  • 349
0

This question has already been asked and answered : What could be the cause of RejectedExecutionException Submitting tasks to a thread-pool gives RejectedExecutionException

This code gives you the error because we try to launch the task but the executor is shut down you can refer to the link above for further explications the answer looked pretty complete:

public class Executorz {

    public static void main(String[] args) {
        Executorz ex = new Executorz();
        ExecutorService es = Executors.newFixedThreadPool(10);

        for (int i = 0; i<100 ; i++){
            System.out.println("Executed");
            es.execute(ex.getNewCountin());

            if (i==20)
                es.shutdown();
        }
    }

    public Countin getNewCountin(){
        return new Countin();
    }

    public class Countin implements Runnable {
        @Override
        public void run() {
            for (double i =0; i<1000000000 ; i++){
            }           
            System.out.println("Done");
        }
    }
}
Community
  • 1
  • 1
Marc
  • 2,621
  • 1
  • 10
  • 13