Java's JVM makes no guarantee that each evaluation of a lambda expression produces a new object instance. Non-capturing lambdas (those that don't reference external variables) can be — and in practice often are — reused as the same instance across multiple calls. This leads to a subtle bug: a factory method returning a non-capturing lambda may return the same object reference every time, causing unexpected behavior when identity matters (e.g., adding to a HashSet yields fewer elements than expected). The post explains the JLS specification behind this behavior, contrasts lambdas with anonymous classes (which always create new instances), and offers practical guidelines: avoid lambdas in factory methods, prefer anonymous or nested classes when identity matters, be cautious with default-method-based functional interfaces, and never rely on undocumented JVM behavior.

9m read timeFrom nipafx.dev
Post cover image
Table of contents
▚ Example▚ Evaluation of Lambda Expressions▚ Lessons Learned▚ Reflection

Sort: