Wednesday, 3 May 2017

Difference between ExecutorService.submit() and Executor.execute() methods in Java?

The main difference between the submit() and execute() method is that ExecuterService.submit() can return the result of computation because it has a return type of Future, but execute() method cannot return anything because it's return type is void.

The core interface in Java 1.5's Executor framework is the Executor interface which defines the execute(Runnable task) method, whose primary purpose is to separate the task from its execution.

Similarities are:
Both ExecutorService.submit() and Executor.execute() methods are used to submit a task to Executor framework for asynchronous execution and both can accept a Runnable task.

Differences are:
1. The submit() method is declared in ExecutorService interface while execute() method is declared in the Executor interface.
2. submit() method can accept both Runnable and Callable task but execute() can only accept the Runnable task.
3. The return type of submit() method is a Future object but return type of execute() method is void.

submit(Callable<T> task)
Submits a value-returning task for execution and returns a Future representing the pending results of the task.

Future<?> submit(Runnable task)
Submits a Runnable task for execution and returns a Future representing that task.

void execute(Runnable command)
Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...