Monday, April 18, 2022

Differences Between Submit and Execute methods

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

OR

Questions: Difference between submit() and execute() method in Java?

Answer : This method are available in java.util.concurrent package. Both methods are used to execute a task to ThreadPool.

                                  Submit                                 Execute
 submit() is a static method of ExecutorService     interface.
Where ExecutorService is sub-interface of Executer interface.
execute() is static  method  declared in Executor interface. 
Executor interface is a parent interface of     ExecutorService.
 Submit() method accepts both Runnable and Callable  task. execute() method accepts only Runnable     task.
Return type of Submit() is Future Object. Return type of execute() is void.
 We can use for submit() if we want to calculate a     larger number of calculations like calculate the value     of factorial of lareg number etc and return results     in computation. We can use for execute() if we want to     execute  our code in parallel by worker threads     of the  Thread pool and does not want to return  anything.

Note: The thread pool created by Executor Class always return a reference of ExecutorService. Which provide access to both submit() and execute() as it also extends Executer interface.
public interface ExecutorService
extends Executor

No comments:

Post a Comment