Video in progress
Do these two lines work the same? What's the difference in when a method reference and a lambda evaluate the receiver object?
class Client {
private Config config; // replaced later in reload()
Supplier<Duration> a() { return config::timeout; }
Supplier<Duration> b() { return () -> config.timeout(); }
}
No. config::timeout evaluates the receiver (config) at the moment the method reference is created: if it's null, the NPE appears immediately on that line, and even if the field is replaced later, the old object is still used. The lambda () -> config.timeout() reads config again on every call.
📖 Answer
There are two differences, and both show up in prod.
1. Null. If config is still null:
a(): aNullPointerExceptionimmediately, on the line where theSupplieris created (the compiler inserts code that null-checks the receiver);b(): theSupplieris created without a problem, and the NPE appears only whenget()is called.
2. Which object is used. A method reference captures the receiver once. A lambda captures this and reads this.config every time:
Supplier<Duration> s1 = client.a();
Supplier<Duration> s2 = client.b();
client.reload(); // config was replaced with a new object
s1.get(); // the timeout of the old config
s2.get(); // the timeout of the new one
I've seen this bug in a project: rateLimiter::acquire was handed to a scheduler, and when the configuration reloaded, a new limiter was created, but the scheduler kept working with the old one.
When to choose which:
- the receiver is immutable (a
finalfield, a local variable): a method reference is shorter and safe; - the receiver may be replaced or is initialized later: use a lambda or go through a getter:
() -> currentConfig().timeout().
The same rule applies to System.out::println: even after System.setOut(...), the method reference keeps writing to the old PrintStream.
Sign up to mark studied questions and save your progress.