什么是capturing lambda

先说下capturing lambda的影响:

在循环里面使用lambda函数造成捕获性lambda后,会产生多余的引用,从而使程序进行原来本可以避免的垃圾回收。从效率的角度上看,这是我们应该避免的。

接下来我们看看什么是capturing lambda。

在学习Disruptor(高性能队列)的时候,它的官方文档有这样一段话:(重点部分已加粗)

ini 复制代码
ByteBuffer bb = ByteBuffer.allocate(8);
for (long l = 0; true; l++)
{
    bb.putLong(0, l);
    ringBuffer.publishEvent((event, sequence) -> event.set(bb.getLong(0)));
    Thread.sleep(1000);
}

This(指上面那段代码) would create a capturing lambda, meaning that it would need to instantiate an object to hold the ByteBuffer bb variable as it passes the lambda through to the publishEvent() call. This will create additional (unnecessary) garbage, so the call that passes the argument through to the lambda should be preferred if low GC pressure is a requirement.

从上面的代码我们可以看到在一个lambda函数 (event, sequence) -> event.set(bb.getLong(0) 里引用到了外部变量bb。那么实际上在虚拟机翻译的时候,首先会在lambda所代表的内部类里生成一个引用,这个引用在内部类构造的时候引用了外面的变量bb(lambda表达式其实就是一个匿名内部类)。

类似于以下代码(我们屏蔽掉disrutor的细节):

arduino 复制代码
        String bb;
        Functional a = new Functional() {
            private final String bb = InnerClass.this.bb;
            @Override
            public void test() {
                System.out.printf(bb);
            }
        };

也就是说在内部类里我们多了一个bb的引用副本,那么在循环的时候,循环多少次就会多几个不必要的bb引用副本。这也是为什么disruptor文档说"This will create additional (unnecessary) garbage",这会增加额外的不必要的垃圾。

那么怎么解决呢?

解决方式就是在lambda的外部类增加一个静态方法,类似于:

arduino 复制代码
    public static void translate(LongEvent event, long sequence, ByteBuffer buffer)
    {
        event.set(buffer.getLong(0));
    }
    public static void main(String[] args) throws Exception
    {
        ByteBuffer bb = ByteBuffer.allocate(8);
        for (long l = 0; true; l++)
        {
            bb.putLong(0, l);
            ringBuffer.publishEvent(LongEventMain::translate, bb);
            Thread.sleep(1000);
        }
    }

和原来的对比一下,方便体会:

ini 复制代码
ByteBuffer bb = ByteBuffer.allocate(8);
for (long l = 0; true; l++)
{
    bb.putLong(0, l);
    ringBuffer.publishEvent((event, sequence) -> event.set(bb.getLong(0)));
    Thread.sleep(1000);
}

相关推荐
‿hhh39 分钟前
微服务智慧交通管理平台 - 项目实现(结合Qoder搭建)
java·人工智能·机器学习·微服务·架构·需求分析·规格说明书
五岳8 小时前
分库分表数据源ShardingSphereDataSource的Connection元数据误用问题分析
java·mysql·爬坑
带刺的坐椅8 小时前
迈向 MCP 集群化:Solon AI (支持 Java8+)在解决 MCP 服务可扩展性上的探索与实践
java·ai·llm·solon·mcp
鼠爷ねずみ8 小时前
SpringCloud前后端整体开发流程-以及技术总结文章实时更新中
java·数据库·后端·spring·spring cloud
代码or搬砖8 小时前
String字符串
android·java·开发语言
AM越.10 小时前
Java设计模式详解--装饰器设计模式(含uml图)
java·设计模式·uml
59803541510 小时前
【java工具类】小数、整数转中文大写
android·java·开发语言
JIngJaneIL10 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
吃喝不愁霸王餐APP开发者10 小时前
Java后端服务在对接全国性霸王餐API时的多数据中心部署与就近调用策略
java·开发语言