Lab 02: GraalVM & Polyglot

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm zchencow/innozverse-java:latest bash


Overview

Explore GraalVM's key innovations: native image compilation via SubstrateVM, the Truffle language framework, and polyglot execution. While native-image requires the GraalVM JDK, all conceptual demos run on Temurin via the ScriptEngine/Nashorn fallback or JavaScript-free equivalents.


Step 1: AOT vs JIT — The Core Tradeoff

Traditional JIT (HotSpot):
  Source → Bytecode → Interpreter → JIT Profile → C2 Optimized
  Startup: slow, Peak throughput: very high, Memory: moderate

GraalVM Native (AOT):
  Source → Bytecode → GraalVM Compiler → Native Binary
  Startup: <50ms (no JVM bootstrap), Memory: -60%, Throughput: lower peak

GraalVM JIT (Graal compiler on JVM):
  Same as HotSpot but uses Graal C++ → Java compiler
  Better partial escape analysis, speculative optimizations
Metric
HotSpot JIT
GraalVM Native

Startup time

500ms–2s

5–50ms

Memory (RSS)

~150MB

~30MB

Peak throughput

★★★★★

★★★☆☆

Dynamic features

Full

Restricted

💡 Native image is ideal for Lambda functions, CLI tools, microservices where startup matters. Use JIT for long-running services needing peak throughput.


Step 2: GraalVM Compiler Architecture


Step 3: SubstrateVM Reflection Configuration

Native image requires explicit reflection configuration — all reflective access must be declared at build time.

💡 Use native-image-agent to auto-generate configuration files: java -agentlib:native-image-agent=config-output-dir=META-INF/native-image -jar app.jar


Step 4: Truffle Language Framework Concepts

Truffle is GraalVM's framework for implementing high-performance language interpreters that automatically get JIT compiled via partial evaluation.


Step 5: Polyglot API Concepts


Step 6: ScriptEngine Fallback on Temurin

Temurin 21 doesn't ship Nashorn but supports the ScriptEngine SPI. We demonstrate the polyglot concept using the expression evaluator pattern:

📸 Verified Output:


Step 7: Native Image Build Process


Step 8: Capstone — AOT Tradeoffs Analysis


Summary

Concept
Technology
Key Points

AOT compilation

native-image

Fast startup, restricted reflection

Truffle AST

TruffleLanguage, Node

Self-optimizing interpreter

Partial evaluation

Graal compiler

Truffle → native code

SubstrateVM

reflect-config.json

Build-time closed-world

Polyglot context

Context.create()

Cross-language objects

JIT vs AOT

HotSpot vs native

Throughput vs startup

native-image-agent

-agentlib:

Auto-generate configs

Last updated