Callable vs Runnable: Understanding Java Concurrency with Future

So far, we used : Runnable But Runnable has a limitation: ❌ It cannot return a result ❌ It cannot throw checked exceptions That’s where Callable comes in. Callable<Integer> task = () -> 10 + 20; Unlike Runnable: ✅ It returns a value ✅ It can throw exceptions Now combine it with ExecutorService: import java.util.concurrent.*; ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Integer> task = () -> 10 + 20; Future<Integer> future = executor.submit(task); System.out.println("Doing other work..."); Integer result = future.get(); // waits if needed System.out.println("Result: " + result); executor.shutdown(); What is Future? A Future represents the result of an asynchronous computation. It allows you to: • Check if task is done → isDone() • Cancel task → cancel() • Get result → get() Important: future.get(); This blocks until result is ready. So even in concurrency, blocking can still happen. The Big Idea Instead of: Run → Wait → Continue We now: Run → Do other work → Collect result later That’s asynchronous thinking. Today was about: • Difference between Runnable & Callable • What Future represents • How asynchronous execution works Modern systems don’t wait. They schedule, continue, and respond when ready. And now… so can your Java programs. #Java #Concurrency #Callable #Future #Multithreading #AsynchronousProgramming #LearningInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories