开发者

RejectedExecutionException in Java Threads

I am writing a multithreaded pro开发者_如何学Pythongram in java. I have written something like this

exec.execute(p)  // where p is a runnable task working on an array
print array
exec.shutdown

The problem I am facing is that the array gets printed giving the correct output but then the rejected Execution Exception comes I don't understand why when the threads have processed and given the correct output why is the error coming...


I think you are shutting down your executor too early. This is an example how I think you should be working.

public class Main {
    public static void main(String[] args) throws Exception {

        // the array to modify
        final int[] array = new int[1000];

        // start the executor (that modifies the array)
        ExecutorService executor = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 1000; i++) {
            final int c = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    array[c] = c;
                }
            });
        }

        // wait for all tasks to quit
        executor.shutdown();
        while (!executor.awaitTermination(10, TimeUnit.SECONDS)); 

        // print the array
        System.out.println(Arrays.toString(array));
    }
}

Also note that working on the same array at the same time could cause inconsistency - you must be really sure that you are not doing work on the array that depends on the array.


Problem is you are still submitting new tasks even after calling shutdown(). So using executor.awaitTermination() won't help.

To fix the problem, check wheather executor is not shutdown at time of submitting task.

example:

if (!executor.isShutdown())
{
  executor.execute(new Runnable() {
                         @Override
                         public void run() {
                              array[c] = c;
                         }
                  });
}

Hope it helps ...


I used to shutdown the executors created in the runtime shutdown hook

Runtime.getRuntime().addShutdownHook(new Thread() {

            public void run() {
            if(!eExecutor.isShutdown()) {
                eExecutor.shutdown();
                // await termination code
              }
            }

        });


One more option could be get the future when you submit to executor and then block on future by calling get

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜