I'm creating an ExecutorService
to execute some tasks which under normal conditions is expected to take one minute to complete but under no circumstances should be allowed to run for more than two minutes from when the task started.
My code is as follows:
ExecutorService executorService = Executors.newFixedThreadPool(10);
ArrayList<Future<?>> futuresList = new ArrayList<Future<?>>();
for (String singleTask: taskList) {
futuresList.add(executorService.submit( new Runnable(){
@Override
public void run(){
try {
performTask(p1, singleTask, p3);
} catch (IOException | InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}));
}
for(Future<?> future : futures) {
future.get(120, TimeUnit.SECONDS);
}
This will block until specified timeout and then move on. My problem(s) are as follows:
1) If task1
blocks for two minutes and task2
also blocks for two minutes - then task2
will have "blocked" for a total of 4 minutes (since future.get(120, TimeUnit.SECONDS);
is not called on task2 until task1
finishes blocking) - even though both tasks were submitted and started executing at the same time
2) If I submit more than 10 tasks, task 11+ may never block for the desired amount of time, if previous tasks have not complete by the time future.get(120, TimeUnit.SECONDS);
is called on the 11th task
My goal is to have each individual task execute for a max of two minutes, regardless of the number of tasks in list and regardless of how many tasks come before it or after it.
Thanks
SingleThreadedExecutor
– HesperidinperformTask
. – Bartizan