When does JVM decide to reuse old lambda?

后端 未结 5 1245
别那么骄傲
别那么骄傲 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:47

    You can't be sure about the identity of the object returned for a lambda expression. It can be a new instance, or a pre-existing instance.

    This is specified in JLS §15.27.4:

    At run time, evaluation of a lambda expression is similar to evaluation of a class instance creation expression, insofar as normal completion produces a reference to an object. Evaluation of a lambda expression is distinct from execution of the lambda body.

    Either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced. If a new instance is to be created, but there is insufficient space to allocate the object, evaluation of the lambda expression completes abruptly by throwing an OutOfMemoryError.

提交回复
热议问题