Java has a modern async feature very similar to Promises in TypeScript, and it’s called CompletableFuture
— it lets you run tasks asynchronously without blocking the main thread and chain actions just like promises.
✅ Analogy: Promise
(TypeScript) ≈ CompletableFuture
(Java)
Here’s how you can use it in Java:
🔧 Non-blocking example with CompletableFuture
import java.util.concurrent.*;
public class Demo {
public static void main(String[] args) {
System.out.println("Main thread started");
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000); // simulate delay
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "Hello from async task!";
}).thenAccept(result -> {
// Runs in a separate thread when the result is ready
System.out.println("Result received: " + result);
});
System.out.println("Main thread continues immediately");
try {
Thread.sleep(2000); // Keep main thread alive for demo
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
✅ Key Benefits of CompletableFuture
- Non-blocking: Doesn’t block main thread like
future.get()
- Chainable: Use
thenApply()
,thenAccept()
,thenRun()
- Exception handling: With
exceptionally()
orhandle()
- Parallel composition: Run multiple async tasks in parallel with
thenCombine()
,allOf()
, etc.
📌 Want to mimic await
?
You can still call .get()
on a CompletableFuture
if you want to wait, similar to await
, but it’s optional.
String result = future.get(); // This is blocking