Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

How should I choose between ExecutorService's submit or execute, if the returned value is not my concern?

If I test both, I didn't see any differences among the two except the returned value.

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();

threadExecutor.execute(new Task());

1 Answer

0 votes
by (46k points)
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).

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 26, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...