I have a controller in which I am using future interface and creating 5 threads in threadpool. This controller is called by an ajax call. When I call this controller the first time it runs fine but if I make the request again it shows the exception below.
java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@1cbbac9 rejected from java.util.concurrent.ThreadPoolExecutor@53ee53[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 5]
I am posting code how I am calling the tasks.
private static final ExecutorService threadpool = Executors.newFixedThreadPool(20);
FactorialCalculator task1 = new FactorialCalculator("A");
FactorialCalculator task2 = new FactorialCalculator("B");
FactorialCalculator task3= new FactorialCalculator("C");
FactorialCalculator task4 = new FactorialCalculator("D");
FactorialCalculator task5= new FactorialCalculator("E");
System.out.println("Submitting Task ...");
Future future1 = threadpool.submit(task1);
Future future2 = threadpool.submit(task2);
Future future3 = threadpool.submit(task3);
Future future4 = threadpool.submit(task4);
Future future5 = threadpool.submit(task5);
System.out.println("Task is submitted");
In first request it is running all tasks- A,B,C,D and E but when I make request again it prints submitting tasks but doesn't print Task is submitted. Can someone help out what am I doing wrong.
You haven't mentioned specifically which version of Java you're using, but I suspect the relevant classes haven't changed much. The ThreadPoolExecutor
will throw that exception from it's execute
method in two cases, both of which rely on the executor's state being SHUTDOWN
.
So I am fairly confident that the executor is rejecting your task submissions because it is being shut down at some point. I notice your code is not telling the whole story, as it looks like the executor is a class field that might be referenced by other methods. Check whether you're calling shutdown anywhere else. (Note that the executor will be shut down by its finalizer; though in the block of code you've posted there's no way it will be eligible for garbage collection as it's a final field.)
As a footnote, whenever you're having trouble with code it's useful to provide a SSCCE. The code you've posted doesn't compile, but after fixing this, it runs successfully. Are you able to fork my Ideone script and reproduce your problem?