先说影响:

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

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

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

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 theByteBuffer bbvariable as it passes the lambda through to thepublishEvent()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的细节):

String bb;Functional a = new Functional() {private final String bb = InnerClass.this.bb;@Overridepublic void test() {System.out.printf(bb);}};

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

那么怎么解决呢?

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

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);}}

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

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);}