Looking at the javadocs it just says
<T> Future<T> submit(Runnable task, T result)
Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return the given result upon successful completion.
Parameters:
task - the task to submit
result - the result to return
but what does it do with result? does it store anything there? does it just use the type of result to specify the type of Future<T>
?
On the other hand, the submit() method is defined in the ExecutorService interface which is a sub-interface of Executor and adds the functionality of terminating the thread pool, along with adding the submit() method which can accept a Callable task and return a result of the computation.
ExecutorService is a JDK API that simplifies running tasks in asynchronous mode. Generally speaking, ExecutorService automatically provides a pool of threads and an API for assigning tasks to it.
You can cancel the task submitted to ExecutorService by simply calling the cancel method on the future submitted when the task is submitted.
It doesn't do anything with the result - just holds it. When the task successfully completes, calling future.get()
will return the result you passed in.
Here is the source code of Executors$RunnableAdapter, which shows that after the task has run, the original result is returned:
static final class RunnableAdapter<T> implements Callable<T> { final Runnable task; final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run(); return result; } }
And yes, the generic type of the result should match that of the returned Future.
Runnable does not return anything and Future must return something so this method allows you to predefine the result of the returned future.
If you don't want to return a thing you can return null and I think the Void
type exists to express that kind of things.
Future<Void> myFuture = executor.submit(myTask, null);
You know myFuture.get()
will return null
in this case but only after the task has been run, so you would use it to wait and throw any exception that were thrown in the task.
try { myFuture.get(); // After task is executed successfully ... } catch (ExecutionException e) { Throwable c = e.getCause(); log.error("Something happened running task", c); // After task is aborted by exception ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With