Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

1. Overview

Chicory is a JVM-native WebAssembly runtime written entirely in Java. It loads .wasm binaries within the JVM, exposes their exports as Java APIs, and eliminates the need for JNI or external native dependencies.

In this tutorial, we’ll run a minimal add.wasm module on the JVM with Chicory. In addition, we’ll run JUnit 5 tests to demonstrate how it works and establish a basic foundation for integrating WebAssembly modules into existing Java applications.

Notably, Chicory requires Java 11 LTS or later.

2. WebAssembly Modules, Imports, and Exports

At the WebAssembly level, everything runs inside a module. A module is a compiled unit that bundles functions, type definitions, and optional memory, tables, and globals into a single .wasm binary. Once compiled, modules are just inert data. Modules become executable only when a host environment instantiates them and turns them into running instances.

A module interacts with the outside world through imports and exports:

  • Imports describe what the module expects the host to provide: for example, a function to log a message or access a clock.
  • Exports describe what the module offers back to the host: functions, memories, tables, or globals that the host can call or read.

In other words, imports are the module’s dependencies, and exports are its public API.

When a module is executed on the JVM, Chicory plays the role of the host runtime. The Java application asks Chicory to parse the .wasm binary into a module, instantiate it, satisfy any imports, and then expose the exports as Java objects that can be called from regular JVM code:

Chicory WebAssembly Java JVM

This way, Chicory is another level of abstraction.

So, let’s keep this graph in mind as the conceptual backdrop for the rest of the article.

3. Quickstart: Running .wasm on the JVM

In this section, we wire up Chicory in a small Maven project, create a tiny WebAssembly module, and call its add() function from a JUnit 5 test.

3.1. Adding the Chicory Runtime Dependency

First, let’s ensure that JUnit 5 and the Maven Surefire plugin are properly configured.

Next, the only additional dependency we need in pom.xml is Chicory’s runtime module, which provides a JVM-native WebAssembly engine:

<dependency>
    <groupId>com.dylibso.chicory</groupId>
    <artifactId>runtime</artifactId>
    <version>1.5.3</version>
</dependency>

Of course, we should check Maven Central for the latest version before copying the snippet.

3.2. Creating .wasm From .wat

For the first example, let’s use a minimal WebAssembly text module that exports a single add function.

Specifically, we save the code add.wat:

(module
    (func (export "add") (param i32 i32) (result i32)
        local.get 0
        local.get 1
        i32.add))

In short, this snippet exports the function add(i32, i32) -> i32: given two 32-bit integers, it returns their sum. There are no imports.

At this point, to turn this code into a .wasm binary, let’s use the online wat2wasm demo and perform several steps:

  1. Start from a clean template by selecting Empty in the example dropdown
  2. Paste the .wat code from above into the text area on the left, replacing any existing content
  3. Leave all options with their default values
  4. Press the Download button to obtain the compiled .wasm

Let’s save the resulting binary in src/test/resources/chicory/add.wasm.

3.3. Instantiating the Module and Calling add(2, 40)

At this point, we can run an initial test:

@Test
void givenAddModule_whenCallingAddWithTwoAndForty_thenResultIsFortyTwo() {
    InputStream wasm = getClass().getResourceAsStream("/chicory/add.wasm");
    assertNotNull(wasm);

    WasmModule module = Parser.parse(wasm);
    Instance instance = Instance.builder(module).build();
    ExportFunction add = instance.export("add");

    long[] result = add.apply(2, 40);

    assertEquals(42, (int) result[0]);
}

Now, let’s take a step-by-step look at how the code above works:

  1. The Parser reads the .wasm binary into an internal module representation
  2. Instance.builder(module).build() turns it into a running instance
  3. instance.export(“add”) gives us an ExportFunction that represents the exported add function
  4. The call to apply(2, 40) returns an array of long values, because WebAssembly functions can return more than one value
  5. We assert that the first result is 42 after downcasting it to int

Now that we’ve covered exports, let’s look at imports to see how a .wasm module requests functionality from the host.

4. Essentials: Imports and Value Types

WebAssembly modules are purely computational until a host provides imports. With Chicory, these imports are fulfilled via host functions written in Java and registered in a Store. When the module is instantiated, Chicory resolves its declared imports against the functions added to the Store. Once resolved, the module can call those host functions during execution.

4.1. A Minimal Import: Calling a Host Function

To begin with, we create a small module that depends on one imported function. The module expects the host double function of type i32 -> i32 and exports a helper that we can call from Java.

Let’s save the sample code as imports.wat and compile it to src/test/resources/chicory/imports.wasm using the wat2wasm demo, as we already did earlier:

(module
    (import "host" "double" (func $double (param i32) (result i32)))
    (func (export "useDouble") (param i32) (result i32)
        local.get 0
        call $double))

Next, we fulfill the import in Java with a host function and instantiate the module using a Store:

@Test
void givenImportDouble_whenCallingUseDouble_thenResultIsDoubled() {
    InputStream wasm = getClass().getResourceAsStream("/chicory/imports.wasm");
    assertNotNull(wasm);

    HostFunction doubleFn = new HostFunction(
            "host",
            "double",
            FunctionType.of(List.of(ValType.I32), List.of(ValType.I32)),
            (Instance instance, long... args) -> new long[] { args[0] * 2 }
    );

    Store store = new Store();
    store.addFunction(doubleFn);

    WasmModule module = Parser.parse(wasm);
    Instance instance = store.instantiate("imports", module);
    ExportFunction useDouble = instance.export("useDouble");

    long[] result = useDouble.apply(21);

    assertEquals(42L, result[0]);
}

So, let’s go through a summary of the logic:

  • Definition of HostFunction doubleFn with the import namespace host, name double, and Wasm signature i32 -> i32
  • doubleFn registered in a Store
  • WasmModule instantiated through the Store
  • ExportFunction useDouble invoked

Let’s visualize how the useDouble call in imports.wasm is linked to the Java HostFunction and how the value flows across the host boundary:

Chicory example - WebAssembly import export flow in Java

Now that the import is in place, let’s look at how the four numeric value types of WebAssembly map to JVM primitives.

4.2. Value Type Mapping at a Glance

Before moving on, we should consider that the WebAssembly primitive function types are numeric only: i32, i64, f32, and f64. Strings, arrays, and structured objects aren’t native Wasm parameters or returns.

In the Chicory low-level API, every call crosses a long-only boundary: parameters are supplied as long, and results are returned as long[]. This array form of the results provides a uniform representation for both single- and multi-result functions. For a single result, we simply read index 0.

Integers are fairly straightforward: i32 values are passed as Java int widened to long, and i64 values as Java long.

Floating-point values require bit-level packing and unpacking at the boundary. For example, we should pass the bits of a Java float via Float.floatToIntBits() after widening them to a long. The same applies to a Java double via Double.doubleToLongBits(). The inverse methods must be applied to the results.

The flow is different for non-numeric data. The module instance, exposed by Chicory as Instance, provides linear memory. Then, we write bytes into it via instance.memory(), pass an offset and length to functions, and decode on the host. For instance, a compact String example using readString(offset, len) is shown in the Chicory Host Functions guide.

5. Troubleshooting: Reading Common Error Messages

When we begin wiring modules and host code, the initial failures typically fall into two categories:

  • unresolved imports at instantiation time
  • missing export names at call time

Let’s examine both with minimal, deterministic tests.

5.1. Unresolved Imports (Instantiation Time)

If a module declares imports and we don’t provide matching host functions with the same names and signatures, instantiation fails. This is exactly what happens when we try to instantiate imports.wasm without registering the host function double: i32 -> i32:

@Test
void whenInstantiatingModuleWithoutRequiredImport_thenErrorIsThrown() {
    InputStream wasm = getClass().getResourceAsStream("/chicory/imports.wasm");
    assertNotNull(wasm);

    WasmModule module = Parser.parse(wasm);

    assertThrows(RuntimeException.class, () -> {
        Instance.builder(module).build();
    });
}

In this case, the fix is to add a HostFunction with the namespace host, name double, and signature i32 -> i32 to the Store, then instantiate through that store, as we did before.

5.2. Missing Export Names (Call Time Lookup)

If instantiation succeeds but we request a function that the module doesn’t export, the lookup fails at call time.

With add.wasm, which only exports add(i32, i32) -> i32, asking for sum triggers an error:

@Test
void whenRequestingMissingExport_thenErrorIsThrown() {
    InputStream wasm = getClass().getResourceAsStream("/chicory/add.wasm");
    assertNotNull(wasm);

    WasmModule module = Parser.parse(wasm);
    Instance instance = Instance.builder(module).build();

    assertThrows(RuntimeException.class, () -> instance.export("sum"));
}

This error typically indicates a typo or an export name mismatch between the WebAssembly module and the host. Once diagnosed, it should be easy to correct.

6. Conclusion

In this article, we set up Chicory on the JVM, compiled a tiny WAT module to add.wasm, and drove the whole flow from JUnit 5. First, we instantiate the module, call its add export, and validate the result. Next, we introduced a minimal import via a Java HostFunction and a Store.

Along the way, we outlined the low-level calling boundary that Chicory exposes. Parameters go in as long and results come back as long[], so integers map directly. On the other hand, floating-point values and non-numeric data require serialization.

Finally, we covered unresolved imports at instantiation time and export name mismatches at call time.

As always, the full code for this article is available over on GitHub.

Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments