Class NativeThread
This class provides low-level Linux thread operations for performance optimization, including CPU affinity pinning to reduce context switching and improve cache locality.
CPU Affinity
Pinning a thread to a specific CPU core provides several benefits:
- Cache locality: L1/L2 cache stays warm on the same core
- Reduced latency variance: No migration between cores
- Predictable performance: Consistent timing for latency-sensitive operations
- NUMA awareness: Can pin to cores near specific memory
Usage Example
\n * // Pin I/O thread to core 2\n * Thread ioThread = new Thread(() -> {\n * NativeThread.pin(2);\n * while (!stopped) {\n * // I/O polling loop\n * }\n * });\n * ioThread.start();\n *
\n *\n *
Platform Requirements
\n *\n *-
\n *
- Linux: Uses
gettid()andsched_setaffinity()\n * - Java: Requires
--enable-native-access=ALL-UNNAMED\n * - Permissions: May require CAP_SYS_NICE for cross-user affinity\n *
Thread Safety
\n *\n *All methods are thread-safe and can be called from any thread.\n * pin(int) should be
called from the thread being pinned.\n
-
Method Summary
Modifier and TypeMethodDescriptionstatic intReturns the kernel thread ID of the current thread.static booleanpin(int cpuId) Pins the current thread to the specified CPU core.
-
Method Details
-
pin
public static boolean pin(int cpuId) Pins the current thread to the specified CPU core.After this call, the thread will only execute on the specified core.\n * This is useful for:\n *\n *
-
\n *
- I/O polling threads (reduces latency variance)\n *
- SQPOLL kernel threads (dedicated CPU for polling)\n *
- Latency-sensitive worker threads\n *
Implementation: Uses Linux
sched_setaffinity()with\n * a cpu_set_t bitmask. Currently supports CPUs 0-63 (single 64-bit word).\n *\n * @param cpuId the CPU core ID (0-based, typically 0 to nproc-1)\n * @returntrueif successful,falseon error\n -
getCurrentThreadId
public static int getCurrentThreadId()Returns the kernel thread ID of the current thread.This is the Linux kernel's thread ID (TID), not the Java thread ID.\n * Useful for debugging and native library interactions.\n *\n * @return the kernel thread ID\n * @throws RuntimeException if the syscall fails\n
-