Log4J2延迟日志中用方法引用替代Lambda是否仍保留懒加载优势?
Great question—this is a common point of confusion, but the short answer is: Yes, using someList::size retains the core lazy logging advantage, just like the Lambda version.
Let me break down why this works clearly:
How Log4j2's Lazy Logging Works
Log4j2 provides overloaded logging methods that accept a Supplier<?> parameter instead of direct values. The key behavior here is:
- Before writing any log output, Log4j2 first checks if the target log level is enabled (e.g., if you call
log.info(), it verifies if INFO-level logging is turned on for the logger). - Only if the level is enabled does it invoke the
Supplier.get()method to retrieve the actual value to log. - If the level is disabled, the
Supplier.get()call never happens—so any computation wrapped inside that supplier is skipped entirely.
Lambda vs. Method Reference: Same Lazy Behavior
Both () -> someList.size() and someList::size are just different syntaxes for creating a Supplier<Integer> instance here:
- The lambda
() -> someList.size()explicitly defines a no-argument function that returns the result ofsomeList.size(). - The method reference
someList::sizeis a concise shorthand for the exact same function—it refers directly to thesize()method of thesomeListinstance, which perfectly matches theSupplier.get()signature (no arguments, returns a value).
In both cases, the size() method is only executed when Log4j2 decides to trigger the supplier (i.e., when the log level is enabled). If the log level is too low (e.g., you're calling log.debug() but debug logging is disabled), neither version will run the size() calculation.
What Would Lose the Lazy Advantage?
The only scenario where you lose the lazy execution benefit is if you pass the computed value directly, like this:
log.info("Size of list is {}.", someList.size()); // No lazy execution!
Here, someList.size() is evaluated immediately, regardless of whether the INFO level is enabled.
So rest assured—using the method reference syntax suggested by your IDE is completely safe and retains all the performance benefits of lazy logging in Log4j2.
内容的提问来源于stack exchange,提问作者Thomas

