Course contentsShow
← Java
Lesson 1669 of 2,87035. Functional InterfacesFree lesson

Lazy Evaluation with Suppliers

How Suppliers enable deferred computation, executing only when get() is called, not when created.

Lazy Evaluation with Suppliers

You'll learn how Suppliers enable deferred computation, executing only when explicitly requested rather than when created.

The Core Concept

When you create a Supplier<T>, you're not computing a value immediately—you're packaging up instructions for how to compute it later. The actual computation only happens when someone calls get(). This is called lazy evaluation or deferred execution.

Think of it like a recipe card versus a cooked meal. A Supplier is the recipe—it describes what to do but doesn't cook anything yet. Only when you call get() does the cooking (computation) actually happen.

Why This Matters

Lazy evaluation is powerful in several scenarios:

1. Expensive Operations

// Computation happens NOW (eager)
String result = performExpensiveOperation();

// Computation happens ONLY when get() is called (lazy)
Supplier<String> lazyResult = () -> performExpensiveOperation();

2. Conditional Execution

Supplier<String> heavyProcess = () -> loadLargeFile();

if (condition) {
    String data = heavyProcess.get();  // Only executes if needed
}
// If condition is false, loadLargeFile() never runs!

3. Repeated Fresh Values

Supplier<LocalDateTime> timestamp = () -> LocalDateTime.now();

timestamp.get();  // Returns current time
Thread.sleep(1000);
timestamp.get();  // Returns NEW current time (re-executed)

Each get() call re-executes the lambda, producing potentially different results for time-dependent or random operations.

Key Takeaway: Suppliers defer computation until get() is invoked, avoiding unnecessary work and enabling on-demand, repeated execution of expensive or dynamic operations.