As of the current JDK 1.8 implementation, it builds an anonymous object to hold the lambda function and calls the function on such object. Is this anonymous object reused in each call, or is an object re-created each time?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
It may be re-used, it may not.
From JLS 15.27.4:
You cannot depend on it to be one or the other. The compiler and/or runtime can choose the one that will give the best result. (This is one of the benefits of lambdas over anonymous classes -- because every time you use
new
, even on an anonymous class, it is guaranteed to be a new object, they are unable to optimize it by re-using it, even though 99% of the time you don't care if they are the same object or not.)In the case where the lambda captures variables from the surrounding scope, it is generally not possible to re-use the object because the value of the captured variables is state stored in the lambda object, and each time the lambda is evaluated (even if it's the same lambda in source code), it may capture different values of the captured variables. Only if the compiler can somehow guarantee that two particular evaluations of the lambda must capture the exact same value of variables, can the compiler re-use the object.
In the case where the lambda does not capture any variables, then all instantiations of that lambda are identical in behavior. So in this case, a single object can be re-used for all evaluations of that lambda. I believe that the current implementation of Java does only allocate one copy for the duration of the program in this case. But this is just an optimization that is implementation-dependent.