Class NativeThread

java.lang.Object
express.mvp.myra.transport.util.NativeThread

public final class NativeThread extends Object
Utility for native thread management using the Foreign Function & Memory API.

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() and sched_setaffinity()\n *
  • Java: Requires --enable-native-access=ALL-UNNAMED\n *
  • Permissions: May require CAP_SYS_NICE for cross-user affinity\n *
\n *\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 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 *
      \n *\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 * @return true if successful, false on 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