Choose Between Executorservice's Submit and Executorservice's Execute

What is the difference between ExecutorService.submit and ExecutorService.execute in this code in Java?

As you see from the JavaDoc execute(Runnable) does not return anything.

However, submit(Callable<T>) returns a Future object which allows a way for you to programatically cancel the running thread later as well as get the T that is returned when the Callable completes. See JavaDoc of Future for more details

Future<?> future = executor.submit(longRunningJob);
...
//long running job is taking too long
future.cancel(true);

Moreover,
if future.get() == null and doesn't throw any exception then Runnable executed successfully

Choose between ExecutorService's submit and ExecutorService's execute

There is a difference concerning exception/error handling.

A task queued with execute() that generates some Throwable will cause the UncaughtExceptionHandler for the Thread running the task to be invoked. The default UncaughtExceptionHandler, which typically prints the Throwable stack trace to System.err, will be invoked if no custom handler has been installed.

On the other hand, a Throwable generated by a task queued with submit() will bind the Throwable to the Future that was produced from the call to submit(). Calling get() on that Future will throw an ExecutionException with the original Throwable as its cause (accessible by calling getCause() on the ExecutionException).

Any difference between ExecutorService.submit and ExecutorService.execute?

Execute() doesn't return a value, whereas submit() returns a Future that can be use to get the return value from the executed code.

execute() is there because it's part of the Executor interface which ExecutorService extends, most likely only so there can be a very simple interface.

What is the difference between submit and execute method with ThreadPoolExecutor

The difference is that execute doesn't return a Future, so you can't wait for the completion of the Runnable and get any exception it throws using that.

ExecutorService submit() - Execute in parallel (non-blocking)

After the invokation to submit you need to invoke awaitTermination. In that way, you will give some time for the task to get executed until a time out defined by you is reached or the execution ends.
Then, you should be able to check the future results by invoking get.

Another option provided by the ExecutorService API is to call invokeAllwhich is a blocking operation that triggers all the tasks. I personally prefer the first option described above.

Update: Also, you didn´t show the ExecutorServiceconfiguration but I assume that you are assigning more than one thread to it. Otherwise, the executions will be sequential no matter what you do after the submit.



Related Topics



Leave a reply



Submit