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

Common Use Cases: Logging and Default Values

Practical scenarios like expensive logging messages and conditional default value computation using Suppliers.

Common Use Cases: Logging and Default Values

You'll learn: How Suppliers shine in real-world scenarios by deferring expensive operations like logging and computing default values only when actually needed.

The Problem with Eager Evaluation

Imagine you're building error messages or computing fallback values. Sometimes these operations are expensive—string concatenation, object creation, or complex calculations—but they're not always used. Without Supplier, you pay the cost upfront, every time.

Use Case 1: Expensive Logging Messages

Logging frameworks often let you pass Supplier<String> instead of plain strings. This way, if the log level is disabled (e.g., DEBUG is off), the message is never built:

// Bad: message built even if DEBUG is disabled
logger.debug("User data: " + expensiveUserDataFetch());

// Good: message built only if DEBUG is enabled
logger.debug(() -> "User data: " + expensiveUserDataFetch());

The Supplier lambda wraps the expensive operation. The logger calls get() only when it needs the message.

Use Case 2: Conditional Default Values

You've seen Optional.orElseGet() before. It accepts a Supplier to avoid creating default objects unnecessarily:

Optional<Configuration> config = loadConfig();

// Always creates new Configuration, even if config exists
Configuration result = config.orElse(new Configuration());

// Only creates Configuration if config is empty
Configuration result = config.orElseGet(() -> new Configuration());

This is crucial when constructing the default is expensive: database queries, file I/O, or heavy object initialization.

The Pattern

Both cases follow the same principle: wrap expensive code in a Supplier so it runs only when needed. Think of it as "pay on demand" instead of "pay upfront."

Key Takeaway: Use Supplier to defer expensive logging messages and default value creation until they're actually required, avoiding unnecessary computation and improving performance.