---
title: Notes on Calling WebAssembly from Java with Chicory
tags: ["Java", "WebAssembly", "Chicory"]
categories: ["Programming", "WebAssembly", "Java", "Chicory"]
date: 2024-07-01T09:09:40Z
updated: 2024-07-01T09:23:40Z
---

> ⚠️ This article was automatically translated by OpenAI (gpt-4o).
> It may be edited eventually, but please be aware that it may contain incorrect information at this time.

[Chicory](https://github.com/dylibso/chicory) is a WebAssembly Runtime on the JVM.
It is implemented purely in Java, and can be used without native libraries or JNI.

> [!NOTE]
> As a Wasm Runtime on the JVM using JNI, there is [wasmtime-java](https://github.com/kawamuray/wasmtime-java).

By adding the following dependency, you can load and execute wasm on a Java application.

```xml
		<dependency>
			<groupId>com.dylibso.chicory</groupId>
			<artifactId>runtime</artifactId>
			<version>0.0.10</version>
		</dependency>
```

Create a sample wasm file from a WAT file. Create the following file `SumSquared.wat`.

It adds two i32 parameters and returns the squared value.

```lisp
(module
  (func (export "SumSquared")
    (param $value_1 i32) (param $value_2 i32)
    (result i32)
    (local $sum i32)

    (i32.add (local.get $value_1) (local.get $value_2))
    local.set $sum
    (i32.mul (local.get $sum) (local.get $sum))
  )
)
```

> [!TIP]
> I used the sample code from [入門WebAssembly](https://www.amazon.co.jp/%E5%85%A5%E9%96%80WebAssembly-Rick-Battagline-ebook/dp/B09MQ6CSBG?crid=2F88E3ZRLB9ML&keywords=webassembly&qid=1688271177&sprefix=WebAssembly%2Caps%2C260&sr=8-6&linkCode=li2&tag=ikam-22&linkId=9a9576034b15b62f172d59f69c3f1784&language=ja_JP&ref_=as_li_ss_il).
> 
> ![入門WebAssembly](https://github.com/making/blog.ik.am/assets/106908/0825cd6a-05f9-4d3a-9e7e-8c3be783709c)

Convert it to wasm using `wat2wasm`.

```
wat2wasm SumSquared.wat 
```

`SumSquared.wasm` will be generated. Load and execute this wasm in Java.

```java
package org.example;

import com.dylibso.chicory.runtime.ExportFunction;
import com.dylibso.chicory.runtime.Instance;
import com.dylibso.chicory.runtime.Module;
import com.dylibso.chicory.wasm.types.Value;

public class Main {
	public static void main(String[] args) {
		Module module = Module.builder("SumSquared.wasm").build();
		Instance instance = module.instantiate();

		ExportFunction iterFact = instance.export("SumSquared");
		Value result = iterFact.apply(Value.i32(2), Value.i32(3))[0];
		System.out.println("Result: " + result.asInt()); // should print "Result: 25" (= (2 + 3)^2)
	}
}
```

Run the Java application.

```
$ mvn -q compile exec:java -Dexec.mainClass=org.example.Main                   
Result: 25
```

The full source code is [here](https://github.com/making/hello-chicory).

It seems to be a good way to incorporate a plugin mechanism into a Java application.
