Java Lambda 表達(dá)式源碼分析

Lambda 表達(dá)式是什么?JVM 內(nèi)部究竟是如何實(shí)現(xiàn) Lambda 表達(dá)式的?為什么要這樣實(shí)現(xiàn)?

基本概念

Lambda 表達(dá)式

下面的例子中,() -> System.out.println("1") 就是一個(gè) Lambda 表達(dá)式。Java 8 中每一個(gè) Lambda 表達(dá)式必須有一個(gè)函數(shù)式接口與之對(duì)應(yīng)。Lambda 表達(dá)式就是函數(shù)式接口的一個(gè)實(shí)現(xiàn)。

@Test
public void test0() {
    Runnable runnable = () -> System.out.println("1");
    runnable.run();

    ToIntBiFunction<Integer, Integer> function = (n1, n2) -> n1 + n2;
    System.out.println(function.applyAsInt(1, 2));

    ToIntBiFunction<Integer, Integer> function2 = Integer::sum;
    System.out.println(function2.applyAsInt(1, 2));
}

大致形式就是 (param1, param2, param3, param4…) -> { doing…… };

函數(shù)式接口

首先要從 FunctionalInterface 注解講起

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

簡(jiǎn)單總結(jié)一下函數(shù)式接口的特征:

  • FunctionalInterface 注解標(biāo)注一個(gè)函數(shù)式接口,不能標(biāo)注類,方法,枚舉,屬性這些。
  • 如果接口被標(biāo)注了 @FunctionalInterface,這個(gè)類就必須符合函數(shù)式接口的規(guī)范。
  • 即使一個(gè)接口沒有標(biāo)注 @FunctionalInterface,如果這個(gè)接口滿足函數(shù)式接口規(guī)則,依舊可以被當(dāng)作函數(shù)式接口。

注意:interface 中重寫 Object 類中的抽象方法,不會(huì)增加接口的方法數(shù),因?yàn)榻涌诘膶?shí)現(xiàn)類都是 Object 的子類。

我們可以看到 Runnable 接口,里面只有一個(gè)抽象方法 run(),則這個(gè)接口就是一個(gè)函數(shù)式接口。

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

方法引用

所謂方法引用,是指如果某個(gè)方法簽名和接口恰好一致,就可以直接傳入方法引用。文章開頭的示例中,下面這塊代碼就是方法引用。

ToIntBiFunction<Integer, Integer> function2 = Integer::sum;

java.lang.Integer#sum 的實(shí)現(xiàn)如下:

public static int sum(int a, int b) {
    return a + b;
}

比如我們計(jì)算一個(gè) Stream 的和,可以直接傳入 Integer::sum 這個(gè)方法引用。

@Test
public void test1() {
    Integer sum = IntStream.range(0, 10).boxed().reduce(Integer::sum).get();
    System.out.println(sum);
}

上面的代碼中,為什么可以直接在 reduce 方法中傳入 Integer::sum 這個(gè)方法引用呢?這是因?yàn)?reduce 方法的入?yún)⒕褪?BinaryOperator 的函數(shù)式接口。

Optional<T> reduce(BinaryOperator<T> accumulator);

BinaryOperator 是繼承自 BiFunction,定義如下:

@FunctionalInterface
public interface BiFunction<T, U, R> {

    R apply(T t, U u);

    default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t, U u) -> after.apply(apply(t, u));
    }
}

可以看到,只要是符合 R apply(T t, U u); 的方法引用,都可以傳入 reduce 中。可以是上面代碼中的 Integer::sum,也可以是 Integer::max。

深入實(shí)現(xiàn)原理

字節(jié)碼

首先寫 2 個(gè) Lambda 方法:

public class LambdaMain {

    public static void main(String[] args) {
        new Thread(() -> System.out.println("1")).start();
        IntStream.range(0, 5).boxed().filter(i -> i < 3).map(i -> i + "").collect(Collectors.toList());
    }
}

之后 javac LambdaMain.java 編譯成字節(jié)碼文件,再通過 javap -p LambdaMain 輸出 class 文件的所有類和成員,得到輸出結(jié)果:

Compiled from "LambdaMain.java"
public class test.jdk.LambdaMain {
  public test.jdk.LambdaMain();
  public static void main(java.lang.String[]);
  private static java.lang.String lambda$main$2(java.lang.Integer);
  private static boolean lambda$main$1(java.lang.Integer);
  private static void lambda$main$0();
}

  • 輸出的 void lambda$main$0() 對(duì)應(yīng)的是 () -> System.out.println("1")
  • 輸出的 boolean lambda$main$1(java.lang.Integer) 對(duì)應(yīng)的是 i -> i < 3
  • 輸出的 java.lang.String lambda$main$2(java.lang.Integer) 對(duì)應(yīng)的是 i -> i + ""

我們可以看出 Lambda 表達(dá)式在 Java 8 中首先會(huì)生成一個(gè)私有的靜態(tài)函數(shù)。

為什么不使用匿名內(nèi)部類?

如果要在 Java 語(yǔ)言中實(shí)現(xiàn) lambda 表達(dá)式,生成匿名內(nèi)部類就可以輕松實(shí)現(xiàn)。但是 JDK 為什么沒有這么實(shí)現(xiàn)呢?這是因?yàn)槟涿麅?nèi)部類有一些缺點(diǎn)。

  1. 每個(gè)匿名內(nèi)部類都會(huì)在編譯時(shí)創(chuàng)建一個(gè)對(duì)應(yīng)的class 文件,在運(yùn)行時(shí)不可避免的會(huì)有加載、驗(yàn)證、準(zhǔn)備、解析、初始化等類加載過程。
  2. 每次調(diào)用都會(huì)創(chuàng)建一個(gè)這個(gè)匿名內(nèi)部類 class 的實(shí)例對(duì)象,無(wú)論是有狀態(tài)的(使用到了外部的變量)還是無(wú)狀態(tài)(沒有使用外部變量)的內(nèi)部類。

invokedynamic

本來(lái)要寫文字的,但是俺發(fā)現(xiàn)俺總結(jié)的思維導(dǎo)圖還挺清晰的,直接提出來(lái)吧,囧。

詳情見 Class LambdaMetafactory 官方文檔,java.lang.invoke.LambdaMetafactory#metafactory 的實(shí)現(xiàn)。

public static CallSite metafactory(MethodHandles.Lookup caller,
                                    String invokedName,
                                    MethodType invokedType,
                                    MethodType samMethodType,
                                    MethodHandle implMethod,
                                    MethodType instantiatedMethodType)
        throws LambdaConversionException {
    AbstractValidatingLambdaMetafactory mf;
    mf = new InnerClassLambdaMetafactory(caller, invokedType,
                                            invokedName, samMethodType,
                                            implMethod, instantiatedMethodType,
                                            false, EMPTY_CLASS_ARRAY, EMPTY_MT_ARRAY);
    mf.validateMetafactoryArgs();
    return mf.buildCallSite();
}

其主要的概念有如下幾個(gè):

  • invokedynamic 字節(jié)碼指令:運(yùn)行時(shí) JVM 第一次到某個(gè)地方的這個(gè)指令的時(shí)候會(huì)進(jìn)行 linkage,會(huì)調(diào)用用戶指定的 Bootstrap Method 來(lái)決定要執(zhí)行什么方法,之后便不需要這個(gè)步驟。
  • Bootstrap Method: 用戶可以自己編寫的方法,最終需要返回一個(gè) CallSite 對(duì)象。
  • CallSite: 保存 MethodHandle 的容器,里面有一個(gè) target MethodHandle。
    MethodHandle: 真正要執(zhí)行的方法的指針。

測(cè)試一下 Lambda 函數(shù)生成的字節(jié)碼,為了方便起見,java 代碼改成如下:

public class LambdaMain {

    public static void main(String[] args) {
        new Thread(() -> System.out.println("1")).start();
    }
}

先編譯成 class 文件,之后再反匯編 javap -c -p LambdaMain 看下輸出:

Compiled from "LambdaMain.java"
public class test.jdk.LambdaMain {
  public test.jdk.LambdaMain();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: new           #2                  // class java/lang/Thread
       3: dup
       4: invokedynamic #3,  0              // InvokeDynamic #0:run:()Ljava/lang/Runnable;
       9: invokespecial #4                  // Method java/lang/Thread."<init>":(Ljava/lang/Runnable;)V
      12: invokevirtual #5                  // Method java/lang/Thread.start:()V
      15: return

  private static void lambda$main$0();
    Code:
       0: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #7                  // String 1
       5: invokevirtual #8                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: return
}

可以看到 Thread 里的 Runnable 實(shí)現(xiàn)是通過 invokedynamic 調(diào)用的。詳細(xì)情況 JVM 虛擬機(jī)規(guī)范,等有時(shí)間再補(bǔ)充吧~~~

總結(jié)

  • Lambda 表達(dá)式在 Java 中最終編譯成私有的靜態(tài)函數(shù),JDK 最終使用 invokedynamic 字節(jié)碼指令調(diào)用。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容