Skip to content

About

NBS — real-time vehicle telemetry from C++ to Java over a lock-free SPSC ring with a single JVM-attached dispatcher thread. Zero dependencies.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

4 Commits

Folders and files

Repository files navigation

NBS — Native Bridge Simulator

Real-time vehicle telemetry from C++ to Java — zero JVM exposure on the producer path

Build C++17 Java 17+ Platform p99 latency License


▶ Watch demo

▶ Click to watch the live dashboard demo


Overview

NBS is a production-grade, zero-dependency testing framework that lets Java applications consume real-time vehicle telemetry emitted by native C++ components — without touching a single line of the vendor's native interface.

Built for the Stellantis automotive architecture, NBS solves a hard systems problem: a legacy vendor engine fires events on threads we don't own, using types we can't modify. Calling Java callbacks directly from those threads crashes the JVM. NBS solves this with a lock-free SPSC ring buffer and a single, dedicated JVM-attached dispatcher thread — completely decoupling the producer path from the JVM.

Key guarantee: producer push() latency is unaffected by JVM activity. p50/p99 are identical whether 0 or 5 heavy Java listeners are registered.

Why this is hard

Constraint Naive approach What breaks
Vendor engine owns its own threads Call env->CallVoidMethod() from the callback Thread is not attached → JVM crash
Attach every callback thread AttachCurrentThread() per event ~10 µs per attach, thread-local churn, detach leaks
Java listener blocks or GCs Invoke listeners inline on the producer thread Producer stalls → vendor engine misses its deadline
Listener throws Let the exception propagate Pending exception corrupts the next JNI call

NBS answers all four with one structural decision: the producer never sees the JVM. Events land in a wait-free ring; one long-lived attached thread drains it.


Contents


Tech Stack

Layer Technology Role
Native core C++17 Lock-free ring buffer, event sources, interceptor, dispatcher, recorder
JNI bridge JNI (C API) Sole crossing point between C++ and JVM — jni_bridge.cpp
JVM Java 17+ (OpenJDK) Consumer API, callback registry, signal catalog, GUI
Build system CMake 3.16+ Compiles libnbs.so / libnbs.dylib + test executables
Build orchestration Bash (build.sh) Single-command build, test, and run for all modes
GUI Java Swing Live dashboard — gauges, indicators, fault injection, replay
Concurrency std::atomic, std::mutex, std::thread Wait-free SPSC ring; dispatcher thread lifecycle
Memory safety AddressSanitizer + UBSan Verified clean under ./build.sh asan
JNI safety -Xcheck:jni Verified zero ref leaks in lifecycle_test
Config YAML (signals.yaml) Single source of truth for signal catalog — custom parsers on both sides, no third-party libs
Serialization CSV Session recording and replay via Recorder / ReplaySource
Platform Linux / macOS Auto-detects .so vs .dylib at build time

System Architecture

NBS System Architecture

The pipeline has three clearly separated zones:

Zone Threads JVM access Responsibility
Sources Producer threads (one per source) ✗ Never Build VehicleEvent PODs, call push()
Ring Buffer Shared memory, no thread ✗ Never Lock-free SPSC hand-off, drop-oldest on full
Dispatcher Exactly one internal thread ✓ Always Drain ring, invoke Java listeners via cached jmethodID + GlobalRef

Dashboard

NBS Swing Dashboard

The Swing dashboard (./build.sh gui) provides live gauges for all 6 signals, drop counter, fault injection buttons, and one-click record/replay.


Threading Contract

This is the core correctness invariant of the entire system.

Thread Owner May touch JVM? Contract
Producer(s) SimSource / ReplaySource / ManualSource → Interceptor NO Only builds POD VehicleEvents and calls push(). push() is wait-free, never blocks, never allocates. Multiple sources are serialized by a short mutex in the interceptor (outside push()) so the strictly-SPSC ring sees exactly one producer.
Dispatcher One internal thread YES AttachCurrentThreadAsDaemon() once on entry, DetachCurrentThread() once on exit. Drains the ring, invokes each listener via a cached jmethodID and a NewGlobalRef'd callback. Catches and clears any Java exception — none ever crosses the boundary.
Control Java threads calling NbsBridge.* via JNI already attached Configure / start / stop / register. Registration takes a mutex; register = NewGlobalRef, unregister = DeleteGlobalRef.

Global-ref invariant: every registered listener is held by exactly one NewGlobalRef and released by exactly one DeleteGlobalRef — on unregister and on shutdown. Verified by lifecycle_test (register 100 → refs 100 → unregister all → refs 0 → shutdown → refs 0) under -Xcheck:jni.

Shutdown sequence (nativeShutdown):

stop sources → drain ring → release all GlobalRefs → DetachCurrentThread → join

Performance

Producer-side push() latency at 10,000 events/sec, measured inside the interceptor around RingBuffer::push() (Apple M-series, Release build):

Scenario p50 p90 p99 max mean
No Java listeners 50 ns 50 ns 400 ns ~16 µs 39 ns
5 busy Java listeners 50 ns 50 ns 400 ns ~7 µs 38 ns

The producer path is completely isolated from JVM activity. p50 and p99 are identical regardless of listener load because producers never cross the thread boundary.

Ring buffer stress (ring_buffer_test): 2,000,000 events through a 1024-slot ring, single producer + single consumer — zero torn reads, strictly increasing delivery, drop-oldest accounting exact.

Run it yourself:

./build.sh loadtest   # 10k events/sec, prints full latency histogram

Quick Start

Prerequisites: cmake, a C++17 compiler, JDK 17+.

# Clone and build everything
git clone https://github.com/Pranav-error/native-bridge-simulator.git
cd native-bridge-simulator
./build.sh            # build + run Phase 1 & Phase 4 tests + logger demo

# Other modes
./build.sh gui        # launch the Swing dashboard
./build.sh loadtest   # 10k/sec load test with latency histogram
./build.sh replay     # record a live session, replay it, verify reproduction
./build.sh asan       # AddressSanitizer + UBSan + -Xcheck:jni
./build.sh logger     # console logger demo (3 seconds)

The native library is libnbs.so (Linux) / libnbs.dylib (macOS). build.sh passes its path automatically via -Djava.library.path and -Dnbs.lib.

Zero external dependencies. signals.yaml is parsed by a purpose-built parser on both sides (catalog.cpp, SignalCatalog.java) — no yaml-cpp, no snakeyaml.


Java API

// 1. Initialize with config and optional ring capacity
NbsBridge.init("config/signals.yaml");          // default 8192-slot ring
NbsBridge.init("config/signals.yaml", 4096);    // custom capacity

// 2. Register listeners (returns opaque id for unregister)
int id = NbsBridge.register((signalId, timestampNs, value, sequence) -> {
    System.out.printf("sig=%d val=%.2f%n", signalId, value);
});

// 3. Start streaming
NbsBridge.startLive();                          // SimSource from YAML
NbsBridge.startReplay("session.csv");           // ReplaySource from recording

// 4. Manual injection (testing / fault simulation)
NbsBridge.inject(0, 120.5);                     // SPEED = 120.5 km/h

// 5. Metrics
long drops = NbsBridge.dropCount();
long[] hist = NbsBridge.pushLatencyNs();        // [p50, p90, p99, max, mean]

// 6. Record / replay
NbsBridge.startRecording("session.csv");
NbsBridge.stopRecording();

// 7. Shutdown — releases all GlobalRefs, joins dispatcher
NbsBridge.shutdown();

The VehicleListener callback is primitive-only — no allocation on the hot path:

@FunctionalInterface
public interface VehicleListener {
    void onEvent(int signalId, long timestampNs, double value, long sequence);
}

Signals

Defined in config/signals.yaml — the single source of truth for both C++ and Java:

ID Name Type Unit Range Rate
0 SPEED float km/h 0–260 50 Hz
1 RPM int rpm 0–8000 50 Hz
2 GEAR enum P/R/N/D/1–6 — 5 Hz
3 BATTERY float % 0–100 1 Hz
4 DOOR_FL bool — — event
5 GPS geo lat/lon — 10 Hz

Adding a new signal

Edit one file, no recompile:

# config/signals.yaml — append at the end (position = signal id)
- { name: COOLANT, type: float, unit: celsius, range: [-40, 130], rate_hz: 2 }

The pipeline is catalog-index driven end-to-end. Restart; the new signal streams.


Design Decisions

Why a lock-free SPSC ring instead of a mutex queue? A mutex on the producer path means the vendor's engine thread can block behind a Java listener that decided to GC. The SPSC ring's push() is two relaxed loads, one store, and one release store — it cannot block, cannot allocate, and cannot be preempted while holding anything. That is what makes the p99 in the table above independent of listener load.

Why drop-oldest instead of blocking or growing? Telemetry is stale-tolerant, deadline-sensitive: a consumer that has fallen 8192 events behind does not want the oldest speed reading, it wants the newest. Blocking would push backpressure onto a thread we don't own; growing would allocate on the hot path. Drops are counted exactly and exposed to Java via dropCount(), so loss is observable rather than silent.

Why exactly one dispatcher thread? AttachCurrentThreadAsDaemon() is expensive and its matching detach is easy to leak. One thread attaches once at startup and detaches once at shutdown — total JVM attach cost for the process lifetime is a single call. It also gives listeners a single well-defined delivery thread, so callbacks are strictly ordered and listeners need no internal locking.

Why cache jmethodID and NewGlobalRef? GetMethodID on every event is a hash lookup into the JVM's method table; a local ref to the callback would die with the frame. Both are resolved once at register(). The invariant — one NewGlobalRef per listener, one DeleteGlobalRef — is what lifecycle_test exists to prove.

Why a hand-written YAML parser? The signal catalog is ~10 lines of flat key-value maps. Vendoring yaml-cpp and snakeyaml to read it would add two dependencies, two build steps, and two license files to a project whose whole point is that it drops into a vehicle build with nothing else attached.

Why primitive-only callbacks? onEvent(int, long, double, long) allocates nothing. Passing a VehicleEvent object instead would put one allocation per event — 10,000/sec — directly in front of the young-gen collector. VehicleEvent.java still exists for code off the hot path.


Testing & Verification

Test Command What it proves
Ring buffer stress ./build.sh 2,000,000 events, 1024-slot ring, 1P/1C — no torn reads, strictly increasing sequence, exact drop accounting
Lifecycle / ref leaks ./build.sh register 100 → refs 100 → unregister → refs 0 → shutdown → refs 0
Memory safety ./build.sh asan AddressSanitizer + UBSan clean; -Xcheck:jni reports zero warnings
Throughput & latency ./build.sh loadtest 10k events/sec sustained, full push-latency histogram
Record / replay fidelity ./build.sh replay Recorded session replays with inter-event deltas preserved
End-to-end ./build.sh gui All 6 signals live, fault injection, drop counter

Exception safety is checked on the delivery path itself: a listener that throws has its exception caught and cleared by the dispatcher before the next listener is invoked — no Java exception ever crosses back into C++.


Project Layout

native/
  include/
    legacy/native_vehicle.h          # UNTOUCHABLE vendor header
    nbs/
      event.h                        # VehicleEvent POD + SignalId enum
      ring_buffer.h                  # Lock-free SPSC ring (header-only)
      source.h                       # IEventSource interface
      interceptor.h                  # Serializes multiple sources → ring
      dispatcher.h                   # The one JVM-attached thread
      recorder.h                     # CSV tap on the drain path
      catalog.h                      # YAML signal catalog
      histogram.h                    # Push-latency histogram
  src/
    legacy_engine.cpp                # Vendor engine (untouched)
    catalog.cpp                      # YAML parser (no yaml-cpp)
    sim_source.cpp                   # Timer-driven simulation
    manual_source.cpp                # JNI-driven injection
    replay_source.cpp                # CSV replay with delta timing
    interceptor.cpp
    dispatcher.cpp
    recorder.cpp
    jni_bridge.cpp                   # All JNI entry points
  test/
    ring_buffer_test.cpp             # Phase 1 graded artifact
    lifecycle_test.cpp               # Phase 4 graded artifact

java/src/main/java/com/nbs/
  NbsBridge.java                     # Public Java API
  VehicleEvent.java                  # Optional value holder (off hot path)
  VehicleListener.java               # Functional interface for callbacks
  CallbackRegistry.java
  SignalCatalog.java                 # Mirrors catalog.cpp
  gui/DashboardFrame.java            # Swing dashboard
  demo/
    LoggerDemo.java
    LoadTest.java
    RecordReplayDemo.java
  testing/RefProbe.java              # Global-ref count probe for lifecycle_test

config/signals.yaml
CMakeLists.txt
build.sh

Troubleshooting

Symptom Cause Fix
UnsatisfiedLinkError: no nbs in java.library.path Java launched without the library path Use ./build.sh <mode> — it sets -Djava.library.path and -Dnbs.lib automatically
JAVA_HOME not found during CMake JDK headers (jni.h) not locatable export JAVA_HOME=$(/usr/libexec/java_home) on macOS, or point it at your JDK root on Linux
Drop counter climbing during loadtest Listeners slower than the 10k/sec producer Expected and correct — drop-oldest is the designed behavior. Lighten listeners or raise ring capacity via NbsBridge.init(cfg, 32768)
Dashboard opens but gauges stay at zero Streaming not started Click Start Live, or confirm config/signals.yaml resolves from your working directory
-Xcheck:jni warnings after adding code A local ref escaped its frame, or a GlobalRef was not released Re-run ./build.sh asan and check every register/unregister pairs exactly once
Replay finishes instantly CSV has no timestamp deltas Record with ./build.sh replay, which produces a properly timestamped nbs_session.csv

Phase Map

Phase Deliverable Key Files
0 CMake → libnbs, JNI round-trip (ping → 4242) jni_bridge.cpp, NbsBridge.ping()
1 Lock-free SPSC ring + stress tests ring_buffer.h, ring_buffer_test.cpp
2 SimSource reads YAML, generates on its own thread sim_source.cpp, catalog.cpp
3 Dispatcher: attach-once, cached jmethodID, GlobalRef dispatcher.cpp, LoggerDemo
4 register/unregister/shutdown, refs→0 under ASan + -Xcheck:jni lifecycle_test.cpp
5 Manual injection Java→C++, all 6 signal types manual_source.cpp, NbsBridge.inject
6 10k/sec load test, push-latency histogram, dropCount to Java LoadTest.java, histogram.h
7 Recorder taps drain → CSV; ReplaySource honors inter-event deltas recorder.cpp, replay_source.cpp
8 Swing dashboard: gauges, indicators, drop counter, fault buttons, replay DashboardFrame.java
9 This README README.md

License

MIT — see LICENSE.

Built for the Stellantis native-to-JVM telemetry challenge.

About

NBS — real-time vehicle telemetry from C++ to Java over a lock-free SPSC ring with a single JVM-attached dispatcher thread. Zero dependencies.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages