JVM什么时候决定重用旧的lambda? [英] When does JVM decide to reuse old lambda?

查看:109
本文介绍了JVM什么时候决定重用旧的lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码片段:

public static Object o = new Object();

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

public static Callable x2() {
    return () -> o;
}

方法 x2()将始终返回相同的lamba对象,而 x1()将始终创建新的:

Method x2() will always return the same lamba object, while x1() will always create new one:

    System.out.println(x1());
    System.out.println(x1());
    System.out.println(x2());
    System.out.println(x2());

会打印出类似这样的内容:

will printout something like this:

TestLambda$$Lambda$1/821270929@4a574795
TestLambda$$Lambda$1/821270929@f6f4d33
TestLambda$$Lambda$2/603742814@7adf9f5f
TestLambda$$Lambda$2/603742814@7adf9f5f

其中(在JVM规范中我猜?)是lambda的这个规则重用描述? JVM如何决定重用与否?

Where (in JVM specification I guess?) is this rule of lambda reuse described? How does JVM decide where do reuse or not?

推荐答案

您无法确定为a返回的对象的身份lambda表达式。它可以是新实例,也可以是预先存在的实例。

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.

这在 JLS§ 15.27.4


在运行时,lambda表达式的计算类似于类实例创建表达式的计算,只要正常完成产生对对象的引用即可。 lambda表达式的求值与lambda体的执行不同。

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.

分配并初始化具有以下属性的类的新实例,或者现有的实例引用具有以下属性的类。如果要创建一个新实例,但没有足够的空间来分配对象,则抛出一个OutOfMemoryError会突然评估lambda表达式。

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.

这篇关于JVM什么时候决定重用旧的lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆