-
Notifications
You must be signed in to change notification settings - Fork 0
Architecture
NAMAN JAIN edited this page Aug 3, 2026
·
1 revision
zThread uses a layered architecture to isolate the public Java API from the underlying native Linux mechanisms. The framework relies on the Java Foreign Function & Memory (FFM) API to avoid JNI overhead.
The system consists of two primary boundaries:
- User Space (Java): Where the developer registers handlers, posts events, and configures the runtime.
-
Kernel Space (Linux): Where the event loop thread sleeps (
epoll_wait) until an event occurs on a file descriptor.
graph TD
subgraph Java Application
A[Producer Thread 1] -->|post| Q(MPSC Ring Buffer)
B[Producer Thread 2] -->|post| Q
H[Event Handlers]
end
subgraph zThread Runtime
Q -->|eventfd signal| EL(Event Loop Thread)
EL -->|dispatch| H
NP(Native Poller) -->|epoll_wait| EL
end
subgraph Linux Kernel
EP[epoll instance]
EF[eventfd]
TF[timerfd]
IF[inotify]
EF --> EP
TF --> EP
IF --> EP
EP -->|wake| NP
end
Provides interface definitions that application developers interact with. It contains no OS-specific logic.
-
ZRuntime: The main interface for starting the loop and posting events. -
ZRuntimeBuilder: Fluent builder for configuration. -
ZRuntimeFactory: SPI interface used by the builder to discover the native implementation at runtime.
Implements the core interfaces using native calls.
-
LinuxRuntime: The concrete implementation ofZRuntime. -
LinuxEventLoop: A dedicated thread that continuously polls for events and drains the MPSC ring buffer. -
LinuxNativePoller: The FFM bridge that links tolibc.so(orlibc.so.6). It handles memory segments forepoll_eventstructs and invokesepoll_create1,epoll_ctl, andepoll_wait.
When a producer thread calls runtime.post(event):
- Insertion: The event is written into a lock-free Multi-Producer Single-Consumer (MPSC) Ring Buffer.
-
Wakeup Signal: If the event loop thread is currently parked in the kernel (
epoll_wait), the producer writes an 8-byte integer to aneventfd. -
Kernel Wakeup: The kernel detects activity on the
eventfd, wakes the event loop thread, and returns control toLinuxNativePoller. -
Drain & Dispatch: The event loop reads the
eventfdto clear the signal, then drains the entire MPSC ring buffer, passing each event to its registered handler sequentially.
- MPSC Ring Buffer: Handles high-throughput, thread-safe queuing of events from multiple producer threads without locking.
- Native Poller: Manages native off-heap memory allocation for Linux structures and executes exact syscalls via FFM.
-
Event Dispatcher: Maintains a map of event types to
Consumer<T>handlers and executes them when the loop drains the buffer.