Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Java Interoperating with Golang

Java Interoperating with Golang

GraalVM
JNI

Avatar for swt02026

swt02026

April 23, 2019
Tweet

More Decks by swt02026

Other Decks in Programming

Transcript

  1. 先決條件 • 不進行兩個語言間的 Struct / Class / Object 傳遞 •

    Java 主動呼叫 Go Binary • 中間產生 Binary 除了 .class 檔,其餘 C ABI 為主 • 不處理非跨平台部分,如 ◦ OS ◦ 專用硬體 ◦ 編譯器預設行為 • 不涉及 JVM 跟 Go Runtime 的 LifeCycle ,如 ◦ Exception ◦ Goroutine ◦ Thread ◦ Garbage Collection ◦ Schedule
  2. Go程式產出 Shared Library • 被使用的 function 加上 "//export <function name>"

    • 執行"go build -buildmode" • 產出 .so 檔與 .h • 此時產出的 .so 符合 C ABI
  3. 方法一: Java Native Interface(JNI) • 利用 JVM 外掛機制,使 Java 程式可以執行

    C 撰寫的程式 • Java 程式 ◦ 針對需要綁定 Native Function 的 Method 加上"native" ◦ 使用"System.loadLibrary" 提示 JVM 執行時要載入的 Library (.so) • 執行 "javah -jni" • 產出 .h 檔,再依照 .h 中的 Prototype 撰寫 .c • 執行 "gcc -fpie -shared",將 C source 轉換成 .so • 使用 JVM 載入 .class 檔,便會自動載入 .so 檔 • Java 程式會動態利用 JVM 的服務,依照 JVM Life Cycle 運作
  4. 方法二: Native Images in Oracle GraalVM • Java AOT Compiler

    的實作 • Java程式加入 Annotation 使 C Header 與 Library 資訊加入 .class檔 • 執行 "javac" 產出 .class檔 • 執行 "native-image" 將 .class 編譯成 Native Object File,此時會進行 Object Linking,解析 .so 中的 Symbol • 執行產出的 Native Object File 則會使用 OS 預設 Loading 行為 • Binary 中原先 JVM 行為,改由 GraalVM 提供的 SubstrateVM 抽象層嵌入 Binary 中(類似 Go Runtime)
  5. JNI vs Native Images JNI • JDK 版本間介面異動不大 • 需要自行撰寫

    C Source • 必須要有 JVM • 需要在 C 程式中使用反射才得以存取 Object/Struct 欄位 Native Images • 新技術,版本間異動較大,較不穩定 • 可直接使用現有的 C ABI Library • 無需 JVM • Native Image 提供 Annotation 綁定需要 的欄位即可
  6. 方法三: 使用 LLVM 生態系 • 使用 llgo 將 go 程式編譯成

    LLVM bitcode • 使用 GraalVM 1. sulong : LLVM bitcode to Truffle AST 2. Polyglot : 隔離 Truffle 與 sulong 之間運作 (Heap address) 3. Truffle : AST Runtime