A high-performance embeddable WebAssembly runtime for Java
Benefits
WebAssembly 1.0 Support
Full WebAssembly 1.0 compatibility and support for many feature extensions, including WASI
Portable Native Extensions
Integrate C, C++, Rust, and Go libraries using Wasm as an alternative to JNI or FFM API
How to Get Started
You have the option to extend your Java application with WebAssembly, or go straight to the starter project
1. Add GraalWasm as a dependency from Maven Central
1. Add GraalWasm as a dependency from Maven Central
<dependency>
<groupId>org.graalvm.polyglot</groupId>
<artifactId>polyglot</artifactId>
<version>24.2.1</version>
</dependency>
<dependency>
<groupId>org.graalvm.polyglot</groupId>
<artifactId>wasm</artifactId>
<version>24.2.1</version>
<type>pom</type>
</dependency>
or
implementation("org.graalvm.polyglot:polyglot:24.2.1")
implementation("org.graalvm.polyglot:wasm:24.2.1")
2. Create a WebAssembly module, for example with wat2wasm
2. Create a WebAssembly module, for example with wat2wasm
;; wat2wasm add-two.wat -o add-two.wasm
(module
(func (export "addTwo") (param i32 i32) (result i32)
local.get 0
local.get 1
i32.add
)
)
3. Embed the Wasm module in Java
3. Embed the Wasm module in Java
import java.net.URL;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
try (Context context = Context.create()) {
URL wasmFile = Main.class.getResource("add-two.wasm");
Value mainModule = context.eval(Source.newBuilder("wasm", wasmFile).build());
Value mainInstance = mainModule.newInstance();
Value addTwo = mainInstance.getMember("exports").getMember("addTwo");
System.out.println("addTwo(40, 2) = " + addTwo.execute(40, 2));
}
import java.net.URL;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
try (Context context = Context.create()) {
URL wasmFile = Main.class.getResource("add-two.wasm");
String moduleName = "main";
context.eval(Source.newBuilder("wasm", wasmFile).name(moduleName).build());
Value addTwo = context.getBindings("wasm").getMember(moduleName).getMember("addTwo");
System.out.println("addTwo(40, 2) = " + addTwo.execute(40, 2));
}