Sobes.tech
Middle

What is the difference between the submit() and execute() methods in a thread pool?

sobes.tech AI

Answer from AI

submit() accepts Runnable or Callable tasks, returning a Future to obtain the result or check the status.

execute() only accepts Runnable tasks and does not provide a return value.

Key differences:

Method Task type Return value Exception handling
execute() Runnable None (void) Exceptions are rethrown in the executor thread
submit() Runnable and Callable Future<?> Encapsulated in Future

Example of using submit() with Callable:

// Example class with a task that returns a result
class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        // Perform some work and return a result
        return "Task completed";
    }
}

//...
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(new MyCallable());
try {
    String result = future.get(); // Blocking call to get the result
    System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}
executor.shutdown();

Example of using execute() with Runnable:

// Example class with a task that does not return a result
class MyRunnable implements Runnable {
    @Override
    public void run() {
        // Perform some work
        System.out.println("Task is running");
    }
}

//...
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new MyRunnable());
executor.shutdown();