Submitting Tasks: Runnable vs Callable
Submit Runnable and Callable tasks, and retrieve results via Future.
Runnable vs Callable
Two functional interfaces represent tasks submitted to ExecutorService:
- Runnable: no return value, cannot declare checked exceptions
- Callable<V>: returns a result of type V, can throw checked exceptions
import java.util.concurrent.*;
// Runnable — no return value
Runnable r = () -> System.out.println("Running");
// Callable<Integer> — returns a value
Callable<Integer> c = () -> {
return 42; // or do computation
};submit(Runnable)
submit(Runnable) returns a Future<?>. Calling get() on it returns null but confirms the task completed (or throws if it failed).
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<?> future = pool.submit(() ->
System.out.println("Task done on " + Thread.currentThread().getName())
);
future.get(); // waits for completion; returns null
System.out.println("Task confirmed complete");
pool.shutdown();All lessons in this course
- ExecutorService and Thread Pool Types
- Submitting Tasks: Runnable vs Callable
- Future and Error Handling
- ScheduledExecutorService for Recurring Tasks