Course contentsShow
← Java
Lesson 2788 of 2,87051. CompletableFutureFree lesson

Introduction to runAsync: Fire-and-Forget Async Tasks

Understand runAsync for executing Runnable tasks asynchronously when no return value is needed.

Introduction to runAsync: Fire-and-Forget Async Tasks

You'll learn how to execute asynchronous tasks that perform actions without returning values using CompletableFuture.runAsync.

What Is runAsync?

While supplyAsync creates asynchronous tasks that compute and return values, runAsync is designed for tasks that do something but don't produce a result. Think of it like pressing a "print" button—you trigger an action, but you don't wait around for a return value. The task runs in the background, and you move on immediately.

Core Concept

runAsync accepts a Runnable (not a Callable) and returns a CompletableFuture<Void>. The Void type signals "this computation completes successfully, but produces nothing." It's perfect for side-effect operations like logging, sending notifications, updating caches, or writing to files where you care that the work happens, but not about receiving data back.

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    System.out.println("Logging event asynchronously...");
    // Perform side-effect work here
});

// Continue immediately without blocking
System.out.println("Main thread continues...");

Fire-and-Forget vs Monitoring

The term "fire-and-forget" means you can start the task and ignore the returned CompletableFuture entirely if you don't care about completion. However, you can still call join() or get() on the returned future if you need to ensure the task finishes before proceeding—though that defeats the async benefit.

Like supplyAsync, runAsync uses the common ForkJoinPool by default, or you can provide a custom executor as a second parameter.

Key Takeaway:
Use CompletableFuture.runAsync when you need to execute asynchronous tasks that perform actions without returning values—it's the fire-and-forget mechanism for async side-effects.