DEV Community

Mario Mastrodicasa
Mario Mastrodicasa

Posted on Originally published at Medium on

JNet in 2026: the JVM and .NET, side by side — three years later

Photo by Timo Volz on Unsplash
Photo by Timo Volz on Unsplash

This is a follow-up to Java APIs written in C# — JVM and .NET side by side. If you are new to JNet, start there.

Three years ago I wrote about JNet — a project that runs a real JVM inside your .NET process and exposes its entire API surface to C#. The core idea has not changed: no byte-code conversion, no TCP channel, no intermediate layer. One process, two runtimes, one boundary.

What has changed is everything around that boundary: how fast it is, how much control you have over it, and what you can do with bulk data crossing it. This article covers what is new.

The ecosystem today

When the first article was published, JNet was essentially a library and a code generator. Today it is the foundation of a larger suite:

  • JNet  — the core library. Almost the full Java API surface, plus any JVM language through JNetReflector.
  • JNetReflector  — points at any JAR and produces production-ready C# classes. In 2023 it was still maturing; today it generates everything: generics, nested types, default and static interface methods, listener wiring, Dispose patterns.
  • KNet  — Apache Kafka APIs for .NET, built entirely on JNet. See the dedicated article.
  • KEFCore  — Entity Framework Core provider for Apache Kafka, built on KNet.
  • JNetPS and JNetCLI  — PowerShell and REPL interfaces to the JVM.

JNetReflector is the common thread. It does the work that used to require manual effort — and now does it well enough that KNet and JNet themselves are generated from it.

JNetReflector: from scaffolding tool to full generator

In 2023 the article mentioned JNetReflector as a promising tool. Today it is the backbone of the entire suite.

Point it at a JAR:

JNetReflector -SourceJar mylib.jar -OutputDirectory ./generated
Enter fullscreen mode Exit fullscreen mode

What comes out is not a skeleton. It is complete, compilable C# — including:

  • Listeners and callbacks with full wiring: the generated class already handles the JVM→.NET event path, delegate registration, and the new two-gate filter (see below).
  • Generics  — including raw-type companions for cases where the concrete type is only known at runtime.
  • Dispose pattern with Interlocked-based thread safety.
  • InvokeWithSignature where the JNI signature is statically known — lower overhead, validation delegated to the JVM.

The original article showed AWT Button as an example. Here is what JNetReflector generates for a listener today — compare with writing it by hand:

// Generated by JNetReflector — no manual work required
public partial class ActionListener : Java.Util.EventListener, IActionListener
{
    // Constructor caches whether ListenerShallManageEvent(int, object) is overridden
    // in a subclass — avoids per-event reflection cost at runtime.
    public ActionListener(params object[] args) : base(args) { ... }

    // First gate - evaluated in order:
    // 1. ListenerShallManageEventIndex delegate (index-based, no string conversion)
    // 2. ListenerShallManageEventName delegate (resolves name via ConvertListenerEventIndexToEventName)
    // 3. ListenerShallManageEventHandlers - true if any handler is registered for this index
    // 4. Falls through to second gate if override detected or WithData delegates are set
    protected override bool ListenerShallManageEvent(int eventIndex) { ... }
    // ActionPerformed: exposed as both a delegate and a virtual method.
    // The delegate takes precedence if assigned; otherwise the virtual is called.
    public Action<Java.Awt.EventNs.ActionEvent> OnActionPerformed { get; set; }
    public virtual void ActionPerformed(Java.Awt.EventNs.ActionEvent arg0) { }
}
Enter fullscreen mode Exit fullscreen mode

The listener works out of the box. The filter hooks are there when you need them.

Controlling what crosses the boundary: the two-gate filter

Every JVM→.NET callback has a cost. When a JVM source fires many event types — an AWT component, a Kafka Streams topology, an OPC-UA subscription — most events may have no registered handler on the .NET side. Without filtering, each event still pays the full cost of argument retrieval and type conversion before being discarded.

JNet 2.6.7+ introduced ListenerShallManageEvent: two virtual methods (and delegate equivalents) that intercept events before data is read.

JVM fires event
       │
       ▼
First gate — ListenerShallManageEvent(int eventIndex)
  false → discard immediately, no data read ~30–35 ns
  true ─────────────────────────────────────────────────┐
                                                         ▼
                               Second gate — ListenerShallManageEvent(int eventIndex, object data)
                                 false → discard, no handler invoked ~144–152 ns
                                 true ──────────────────────────────────────────────────────┐
                                                                                             ▼
                                                                              Full handler invocation
                                                                                       ~2.7 µs
Enter fullscreen mode Exit fullscreen mode

The fastest path uses ListenerShallManageEventIndex — it receives the raw integer event index with no string conversion:

var listener = new ActionListener();
// First gate: only process actionPerformed (index 0), discard all others
listener.ListenerShallManageEventIndex = eventIndex => eventIndex == 0;
// Second gate: inspect raw data before committing to full processing
listener.ListenerShallManageEventIndexWithData = (eventIndex, data) =>
{
    // data is CLRListenerEventArgs - cast and inspect without full conversion
    return ShouldProcess(data);
};
listener.ActionPerformed += e => Console.WriteLine(e.ActionCommand);
Enter fullscreen mode Exit fullscreen mode

Or via virtual override in a subclass — JNetReflector handles the wiring either way.

Performance: numbers from the boundary

All numbers below are from GitHub Actions (ubuntu-22.04, AMD EPYC 9V45), 1 000 000 iterations, JCOBridge 2.6.9. Full tables on the JNet performance page.

Method invocation

Scenario Invoke InvokeWithSig Invoke InvokeWithSig
                     fb=false fb=false fb=true fb=true
------------------------------------------------------------------------------
Static (.NET 8) 0.313 µs 0.248 µs 0.471 µs 0.311 µs
Instance (.NET 8) 0.189 µs 0.162 µs 0.389 µs 0.287 µs
Static (.NET 10) 0.265 µs 0.250 µs 0.482 µs 0.305 µs
Instance (.NET 10) 0.176 µs 0.178 µs 0.390 µs 0.307 µs
Enter fullscreen mode Exit fullscreen mode

Instance method invocation with InvokeWithSignature reaches 162 ns on .NET 8 and 178 ns on .NET 10 — down from ~468 ns in 2.6.6, a −65% reduction over two years.

Callback (JVM → .NET, sustained stream)

Path .NET 8 .NET 10
---------------------------------------------------------------------
Full processing 2.674 µs 2.750 µs
First gate discard 0.035 µs 0.030 µs
(ListenerShallManageEventIndex)

Second gate discard 0.144 µs 0.152 µs
(raw data inspected)
Enter fullscreen mode Exit fullscreen mode

The first-gate discard at 30–35 ns is within the range of raw JNI overhead measured on dedicated hardware — despite the additional CLR interop layer and a shared CI runner.

Where the improvement came from

The largest single gain in 2.6.9 came from a simple structural fix: an internal buffer used by the dispose fast-scope path was previously allocated on every event. Making it a pooled, thread-local resource that survives across scopes eliminated ~1M array allocations per test and reduced total test time from ~23s to ~14s.

Bulk data: reading JVM memory from .NET

When a JVM method returns an array — audio samples, sensor readings, a Kafka record payload — the standard path copies that array across the JNI boundary into a new .NET byte[]. For large payloads this copy dominates.

JCOBridge 2.6.9 introduces two typed wrappers:

  • JCOBridgeStream  — wraps a JVM native array. Exposes UnmanagedMemoryStream, ReadOnlySpan, and .NET Framework-compatible shims.
  • JCOBridgeDirectBuffer  — wraps a JVM DirectByteBuffer. Same surface. Because a DirectByteBuffer lives in native (off-heap) memory, AsSpan() is zero-copy in all editions  — no HPA required.

JNetReflector does not generate xxxStream() variants for every method — the limitation is fundamental: with a generic type like Map, the concrete array type of V is only known at runtime. Instead, you obtain JCOBridgeStream from the raw type companion that JNetReflector generates alongside every generic:

// Via Convert<T>() extension on the raw return value
var value = entry.Value; // object (raw type)
using JCOBridgeStream<byte> stream = value.Convert<JCOBridgeStream<byte>>();
ReadOnlySpan<byte> span = stream.AsSpan(); // zero-copy with HPA
// Or via IJavaArray.ToStream<T>()
var array = entry.Value as IJavaArray;
using JCOBridgeStream<byte> stream = array.ToStream<byte>(FileAccess.Read, true);
Enter fullscreen mode Exit fullscreen mode

Inside a listener’s second gate, the same pattern lets you inspect array contents before deciding whether to invoke the handler:

protected override bool ListenerShallManageEvent(int eventIndex, object data)
{
    var result = data as CLRListenerEventArgs<JNetEventResult>;
    IJavaObject firstParam = result.EventData[0];
    using (firstParam)
    using (IJavaArray array = firstParam.ToJavaArray())
    using (JCOBridgeStream<byte> stream = array.ToStream<byte>())
    {
        ReadOnlySpan<byte> span = stream.AsSpan();
        return ShouldProcess(span); // inspect without allocating a .NET array
    }
}
Enter fullscreen mode Exit fullscreen mode

Performance (100 iterations, ubuntu-22.04)

API 1 KB 1 MB 100 MB
----------------------------------------------------------------------
Invoke<byte[]> (copy) 2.7 µs 205.9 µs 14,635.8 µs
JCOBridgeStream / AsSpan 2.6 µs 214.9 µs 14,384.0 µs
DirectByteBuffer / AsSpan 2.7 µs 31.1 µs 5,590.3 µs
DirectByteBuffer / ToStream naive 6.5 µs 608.1 µs 38,873.0 µs
Enter fullscreen mode Exit fullscreen mode

DirectByteBuffer + AsSpan reaches 17.9 GB/s at 100 MB. The naive MemoryStream pattern is 7× slower at 100 MB — avoid it.

HPA and zero-copy for JVM arrays

JCOBridgeStream with the standard edition still makes an internal copy. With the HPA edition , AsSpan() accesses JVM array memory directly — GC pinned for the duration, no copy. Check JCOBridge.IsHPAEdition at startup:

if (JCOBridge.IsHPAEdition)
{
    // AsSpan() on JCOBridgeStream<T> is truly zero-copy
}
Enter fullscreen mode Exit fullscreen mode

The DirectByteBuffer benchmark (pre-allocated native memory, no heap→native copy) shows what HPA-level performance looks like for array access — the same absence of copy that HPA achieves for JVM arrays.

What has not changed

The foundation is the same as in 2023:

  • One JVM per process, started at CreateGlobalInstance().
  • No marshalling, no TCP, no byte-code conversion.
  • The JVM you choose — Temurin, GraalVM, Azul — with the version you need.
  • AWT/Swing still works, still embeddable in WinForms and WPF.

The AWT example from the original article compiles and runs unchanged today.

Where to go from here

Benchmark environment: GitHub Actions ubuntu-22.04, AMD EPYC 9V45 96-Core, JCOBridge 2.6.9, 1 000 000 iterations. Full methodology and tables at the link above.

Top comments (0)