So I’ve written a block of code that will submit an array of objects through a task handler, I had an instance come up where the program crashed and did not close properly… Will this code do what I’m thinking it should?
In my mind the following code should take an object, pass it to a handler, and then wait until a maximum of 30s has passed, and if that thread hasn’t completed, kill it. Right?
//Iterate through the array to submit them into individual running threads.
ExecutorService threadPool = Executors.newFixedThreadPool(12);
List<Future<?>> taskList = new ArrayList<Future<?>>();
for (int i = 0; i < objectArray.length; i++) {
Future<?> task = threadPool.submit(new ThreadHandler(objectArray[i], i));
taskList.add(task);
Thread.sleep(500);
}
//Event handler to kill any threads that are running for more than 30 seconds (most threads should only need .25 - 1 second to complete.
for(Future future : taskList){
try{
future.get(30, TimeUnit.SECONDS);
}catch(CancellationException cx){ System.err.println("Cancellation Exception: "); cx.printStackTrace();
}catch(ExecutionException ex){ System.err.println("Execution Exception: ");ex.printStackTrace();
}catch(InterruptedException ix){ System.err.println("Interrupted Exception: ");ix.printStackTrace();
}
}
threadPool.shutdown(); // SHUT. DOWN. EVERYTHING.
No it won’t, you’re just not waiting for them to finish anymore. Use
cancelto kill it for good:Also you should make sure the executor finished after calling
shutdown: