Saturday, 1 June 2019

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

This is one of the good multi-threading concepts for experienced Java programmers. The main difference between submit() and execute() method is, ExecuterService.submit() can return the result of computation because it has a return type of Future, however, execute() method cannot return anything as 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. 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 submit() method which can accept a Callable task and return a result of the computation.

Similarities between execute() and submit() methods
1) Both submit() and execute() methods are used to submit a task to Executor framework for asynchronous execution.
2) Both submit() and execute() can accept a Runnable task.
3) You can access submit() and execute() from the ExecutorService interface because it also extends the Executor interface which declares the execute() method.

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

When to use submit() and execute() method in Java

After understanding the difference between Executor.execute() and ExecutorService.submit() method, we can decide when to use submit() and when to use the execute() method.

In general, if you are doing computational task e.g. calculating some risk stats, calculating factorial of large numbers or doing some time-consuming computation which results in some value then use the submit() method. It immediately returns a Future object, which can be later queried to get the value of computation by calling get() method. Termination of batch jobs can we identified by using the Future which can be returned by submit method only. Remember, get() is a blocking call so always call the version which accepts a timeout.

While you can use the execute() method if you just want your code to be run in parallel by worker threads of the thread pool.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...