When does JVM decide to reuse old lambda?

后端 未结 5 1241
别那么骄傲
别那么骄傲 2020-12-15 05:24

Consider the following code fragment:

public static Object o = new Object();

public static Callable x1() {
    Object x = o;
    return () -> x;
}

publi         


        
5条回答
  •  天涯浪人
    2020-12-15 05:50

    There is no way for the compiler to optimise x1() to return the same lambda -- the behaviour would then be different. Since o is not final, the lambda returned needs to capture the state of that field (with the x variable) as its value could change between calling x1() and invoking the returned lambda.

    That's not to say that there aren't situations where the compiler theoretically could reuse the instance but doesn't (the other answers give some insight into that) -- only that this isn't one of those cases.

提交回复
热议问题