Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)
What is the difference between Runnable, Callable, and Future in Java Concurrency?
senior LevelCode ExampleSystem Design
In Simple Words:
Runnable: Represents a task that runs asynchronously on a thread. Itsrun()method returns void and cannot throw checked exceptions.Callable<V>: Represents an asynchronous computation. Itscall()method returns a typed valueVand can throw checked exceptions.Future<V>: Represents the eventual result of an asynchronous computation. It provides methods to inspect if the computation is complete (isDone()), cancel it (cancel()), or block waiting for the result (get()).
java
ExecutorService executor = Executors.newFixedThreadPool(2);
Callable<Integer> calculationTask = () -> {
Thread.sleep(100);
return 42 * 2;
};
Future<Integer> future = executor.submit(calculationTask);
// Blocking get with timeout:
Integer result = future.get(1, TimeUnit.SECONDS);
System.out.println("Computed result: " + result);
executor.shutdown();
Limitation of Future:
A standard Future cannot be chained (no callbacks like thenApply) and has no way to combine multiple independent futures without blocking thread resources.