I'm trying to run a task in parallel. I have tried the following:
In my constructor:
this.executor = Executors.newFixedThreadPool(5);
executor.awaitTermination(10, TimeUnit.SECONDS);
then I add all the items I want to run in parallel to a list:
Future<Map.Entry<Location, SomeData>> result = this.executor.submit(new Sender(entry));
resultList.add(result);
Then I loop on that list and use the get()
function of Future
in order to execute each task - which appears to be blocking:
for (int i = 0; i < resultList.size(); i++) {
Future<Map.Entry<Location, SomeData>> result = resultList.get(i);
try {
logger.info("[Start] Task" + sendQueue.get(i).getKey() + "-" + i);
entry = result.get();
} catch (InterruptedException e) {
logger.error("Interrupted error", e);
} catch (ExecutionException e) {
logger.error("Thread Execution error", e);
} catch (Exception e) {
logger.error("Send Error", e);
}
if (entry == null) {
logger.error("Telemetry Send Error");
return;
}
logger.info("[Success] Task" + entry.getKey() + "-" + i);
}
Sender call():
@Override
public Map.Entry<Location, Data> call() throws InterruptedException {
Thread.sleep(5000);
return this.entry;
}
I see that each task is executed after the other. I want to execute all tasks in parallel and make it non-blocking.
Any idea what I'm missing? Isn't it what the executor service used to do?
After the invokation to submit
you need to invoke awaitTermination
. In that way, you will give some time for the task to get executed until a time out defined by you is reached or the execution ends. Then, you should be able to check the future results by invoking get
.
Another option provided by the ExecutorService
API is to call invokeAll
which is a blocking operation that triggers all the tasks. I personally prefer the first option described above.
Update: Also, you didn´t show the ExecutorService
configuration but I assume that you are assigning more than one thread to it. Otherwise, the executions will be sequential no matter what you do after the submit
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.