Sobes.tech
Middle

Can submit be used to run only Runnable or also Callable?

sobes.tech AI

Answer from AI

The submit method from ExecutorService in Java can accept both Runnable and Callable.

  • If you pass a Runnable, the method returns a Future<?>, which can be used to track the completion of the task, but the result will be null.
  • If you pass a Callable<V>, then submit returns a Future<V>, where V is the type of the result returned by the task.

Example:

ExecutorService executor = Executors.newFixedThreadPool(2);

// Runnable
Future<?> future1 = executor.submit(() -> System.out.println("Runnable task"));

// Callable
Future<Integer> future2 = executor.submit(() -> {
    Thread.sleep(1000);
    return 42;
});

Integer result = future2.get(); // result will be 42
executor.shutdown();