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

getNow: Non-Blocking Result Retrieval

Retrieving a CompletableFuture's result immediately if available, or a default value if not yet complete.

getNow: Non-Blocking Result Retrieval

You'll learn how to retrieve a CompletableFuture's result immediately without blocking, or get a fallback value if it's not ready yet.

The Core Idea

Unlike get() and join() which block your thread until a result is available, getNow(T valueIfAbsent) checks the CompletableFuture's status right now and returns either:

  • The actual result, if the computation completed successfully
  • The fallback value you provide, if the computation is still running or hasn't started

Think of it like checking your mailbox: get() means standing at the mailbox until the mail arrives (blocking), while getNow() means checking once and grabbing a backup newspaper if nothing's there yet (non-blocking).

When to Use getNow

This method is perfect when you need to poll for results without stalling your thread:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // Expensive computation
    return "Computed Result";
});

// Check immediately without blocking
String result = future.getNow("Still computing...");
System.out.println(result); // Likely prints "Still computing..."

// Later, after completion
Thread.sleep(1000); // Simulating time passing
String finalResult = future.getNow("Still computing...");
System.out.println(finalResult); // Prints "Computed Result"

Choosing Your Fallback Value

The fallback you provide should represent a sensible "not ready" state for your application—perhaps null, an empty string, or a special sentinel value that your code can recognize.

Key Takeaway: getNow(valueIfAbsent) provides instant, non-blocking access to a CompletableFuture's result, returning your specified default value if the computation hasn't finished yet—ideal for polling or checking status without waiting.