Java Asynchronous Programming

๐ Introduction
Section titled โ๐ Introductionโ๐ What is Asynchronous Programming?
Section titled โ๐ What is Asynchronous Programming?โAsynchronous programming allows tasks to run in the background without stopping the main thread. This enables:
- ๐งต Non-blocking execution
- โก Better resource use
- ๐ป Smooth user interfaces
- ๐ High scalability for concurrent tasks
- Goal โ better responsiveness and parallelism
๐ Synchronous vs Asynchronous
Section titled โ๐ Synchronous vs Asynchronousโ| Feature | Synchronous | Asynchronous |
|---|---|---|
| Execution | Blocking, sequential | Non-blocking, concurrent |
| Thread Usage | Single | Multiple |
| UI Responsiveness | May block | Remains responsive |
| Complexity | Simple | Requires more control |
| Error Handling | try-catch | callbacks, handlers |
โ When to Use Async Code
Section titled โโ When to Use Async Codeโ- I/O operations (network, file, DB)
- CPU-heavy tasks (math, ML)
- UI apps (to avoid freezing)
- Backend services (handle many requests)
๐ Example (Real-life analogy):
-
Synchronous: Order coffee โ wait until itโs made โ then do other work.
-
Asynchronous: Order coffee โ work on laptop โ barista notifies you when coffee is ready.
โ๏ธ Callable Interface (Why not Runnable?)
Section titled โโ๏ธ Callable Interface (Why not Runnable?)โโ Callable vs Runnable
Section titled โโ Callable vs Runnableโ| Feature | Callable | Runnable |
|---|---|---|
| Returns value | โ
Yes (V) | โ No |
| Throws Exception | โ Yes (checked exceptions allowed) | โ No (only unchecked) |
| Generics | โ Supports generics | โ No |
| Introduced in | Java 5 | Java 1.0 |
๐ Overview
Section titled โ๐ Overviewโ-
Callable<V>is likeRunnablebut:-
Can return a result (
V) -
Can throw checked exceptions
-
-
Designed for asynchronous tasks that produce a result.
โจ Key Features
Section titled โโจ Key Featuresโ-
โ Returns result (
V) -
โ Can throw checked exceptions
-
๐ง Uses generics for type safety
Future & Callable
Section titled โFuture & Callableโ-
Runnablecannot return results. -
Callablecan return a value + throw exceptions. -
Futureholds the result of asynchronous computation.
โ๏ธ Callable Interface (Why not Runnable)
Section titled โโ๏ธ Callable Interface (Why not Runnable)โimport java.util.concurrent.*;
public class CallableExample { public static void main(String[] args) throws Exception { Callable<String> task = () -> "Hello from Callable!";
FutureTask<String> future = new FutureTask<>(task); new Thread(future).start();
String result = future.get(); // Waits for result System.out.println(result); }}๐ฎ Future Interface
Section titled โ๐ฎ Future InterfaceโFuture represents the result of an async task, which will be available later.
๐ Key Methods
Section titled โ๐ Key Methodsโget()โ wait for resultcancel()โ try to stopisDone()โ check completionisCancelled()โ check cancel
๐ฆ Example
Section titled โ๐ฆ ExampleโFuture<Integer> f = executor.submit(() -> 42);Integer result = f.get(); // Waits hereโณ Timeout Example
Section titled โโณ Timeout Exampleโfuture.get(2, TimeUnit.SECONDS); // Throws TimeoutException if lateโ ๏ธ Limitations of Future
Section titled โโ ๏ธ Limitations of Futureโ-
โ
get()is blocking โ doesnโt feel truly async -
โ No built-in chaining (cannot say do this after completion)
-
โ No easy error handling (exceptions wrapped in
ExecutionException) -
โ Cannot combine multiple futures (e.g., wait for both Task A & B)
๐ Thatโs why CompletableFuture (Java 8+) was introduced to overcome these issues.
โ CompletableFuture
Section titled โโ CompletableFutureโ
๐ Overview
Section titled โ๐ OverviewโCompletableFuture improves on Future by adding:
- โ Non-blocking chaining
- ๐ Composability
- ๐ฅ Error handling
- ๐งช Manual completion
๐ Key Features
Section titled โ๐ Key Featuresโ| Feature | Description |
|---|---|
thenApply | Transforms result |
thenAccept | Consumes result (no return) |
exceptionally | Handle errors |
thenCombine | Combine multiple futures |
allOf, anyOf | Wait for all/any futures |
๐งช Basic Example
Section titled โ๐งช Basic ExampleโCompletableFuture.supplyAsync(() -> "Hi") .thenApply(data -> data.toUpperCase()) .thenAccept(System.out::println);๐ Chaining & Error Handling
Section titled โ๐ Chaining & Error HandlingโUse thenCompose() to chain dependent tasks, and exceptionally() to handle errors.
๐ Combining Multiple Futures
Section titled โ๐ Combining Multiple FuturesโthenCombine(f2, (a, b) -> a + b);CompletableFuture.allOf(f1, f2).join();๐งต Manual Completion
Section titled โ๐งต Manual CompletionโCompletableFuture<String> future = new CompletableFuture<>();future.complete("Done"); // Manually set result