Difference between Submit() Vs Execute()

Difference between the Submit() and Execute()

 In Java, both the submit() vs execute() methods are used to submit tasks to a thread pool for execution, but they have some differences in their behavior and return types.

Submit() Vs Execute()

1. submit() Method:

  • The submit() method is part of the ExecutorService interface and is used to submit tasks that return a result.
  • It accepts tasks as Callable or Runnable objects submit() vs execute() and returns a Future representing the result of the computation.
  • The Future object allows you to check the status of the submitted task, retrieve the result if available, or cancel the task.
  • If the task throws an exception, it is wrapped in the Future, and you can handle the exception when retrieving the result submit() vs execute().
  • This method provides better support for handling exceptions and getting results from submitted tasks.

2. execute() Method:

  • The execute() method is part of the Executor interface and is used to submit tasks that do not return a result (i.e., Runnable tasks).
  • It does not return a value or provide a way to check the status or result of the submitted task.
  • If the task throws an unchecked exception, it is caught and logged by the thread pool’s uncaught exception handler.
  • This method is simpler and more suitable for fire-and-forget tasks where you don’t need to wait for the result or handle exceptions explicitly.

Example
java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // Using submit() method
        Future<String> futureResult = executor.submit(() -> {
            Thread.sleep(1000); // Simulate some computation
            return "Result from submit() method";
        });

        // Using execute() method
        executor.execute(() -> {
            try {
                Thread.sleep(1000); // Simulate some computation
                System.out.println("Task executed using execute() method");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // Shutdown the executor
        executor.shutdown();
    }
}

Example

In this example, we create a fixed-size thread pool using Executors.newFixedThreadPool(2) and submit tasks using both submit() and execute() methods. The task submitted using submit() returns a Future representing the result of the computation, while the task submitted using execute() does not return a value. Additionally, the Submit() Vs Execute() allows us to handle exceptions and retrieve results from the submitted task, whereas the execute() method does not provide such functionality.

Homepage

Readmore