Reputation:
I am writing a multithreaded program 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...
Upvotes: 7
Views: 13254
Reputation: 20623
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
}
}
});
Upvotes: 2
Reputation: 614
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 ...
Upvotes: 6
Reputation: 637
One more option could be get the future when you submit to executor and then block on future by calling get
Upvotes: 0
Reputation: 43504
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.
Upvotes: 12