New to submit method of Java concurrent framework. Wondering whether the thread got executed when I call submit or when I call get? Researched Oracle official document, but cannot find too much information. Thanks.
I am referring to the sample below,
http://www.vogella.com/tutorials/JavaConcurrency/article.html
package de.vogella.concurrency.callables;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableFutures {
private static final int NTHREDS = 10;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
List<Future<Long>> list = new ArrayList<Future<Long>>();
for (int i = 0; i < 20000; i++) {
Callable<Long> worker = new MyCallable();
Future<Long> submit = executor.submit(worker);
list.add(submit);
}
long sum = 0;
System.out.println(list.size());
// now retrieve the result
for (Future<Long> future : list) {
try {
sum += future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println(sum);
executor.shutdown();
}
}
No, calling submit doesn't execute the task. And calling get doesn't execute the task. The task is processed asynchronously in a thread belonging to the executor's threadpool.
Calling the submit method gives a task to a threadpool. The task is queued up until one of the threads in the pool is free. Then the pool assigns the task to the worker thread, which invokes the code.
When you call Future.get, then either a worker has finished processed your task, a worker is currently processing your task, or the task is still queued up waiting for a worker to become available. If your task is done then the future returns the value returned from the Callable task, otherwise calling the future's get method causes your main thread to block until the task is finished.