Understanding Java Thread Implementation and CPU Affinity with OpenHFT Java-Thread-Affinity
The article explains Java's underlying thread models, why native methods are used, and how the OpenHFT Java-Thread-Affinity library leverages JNA to bind Java threads to specific CPU cores for performance gains, including code examples and real‑world usage.
Java Thread Models
Java's Thread class relies heavily on native methods, meaning the actual thread handling is delegated to the operating system. Three classic models exist: 1:1 kernel threads, 1:N user threads, and N:M hybrid threads. The HotSpot JVM typically uses the 1:1 model, mapping each Java thread directly to an OS native thread.
Why Bind Threads to CPUs?
Binding (affinity) is an OS‑level operation; Java itself cannot directly control it. By fixing a thread to a specific core you can improve cache locality and reduce context‑switch overhead, which is valuable for high‑performance workloads.
OpenHFT Java-Thread-Affinity Library
The open‑source project provides a Java wrapper around native APIs (via JNA) to set thread affinity. It supports Linux (using taskset ) and Windows (using SetThreadAffinityMask from kernel32.dll ).
Dependency example:
<dependency>
<groupId>net.openhft</groupId>
<artifactId>affinity</artifactId>
<version>3.2.3</version>
</dependency>Simple usage demo:
public static void main(String[] args) {
try (AffinityLock lock = AffinityLock.acquireLock(5)) {
// do some work while locked to a CPU
while (true) {}
}
}This code locks the current thread to CPU core 5, driving its utilization to 100% as shown in the accompanying GIFs.
How It Works Internally
The library detects the OS at class initialization and loads the appropriate native implementation (e.g., WindowsJNAAffinity uses JNA to call kernel32.dll 's SetThreadAffinityMask ).
Binding is performed by setting a bit in a BitSet representing the target CPU and then invoking the native API.
On Solaris the library currently provides a no‑op implementation because HotSpot can already handle both 1:1 and N:M models.
Adoption in Real Projects
Netty and SOFAJRaft both depend on this library to achieve fine‑grained thread placement. It was also used in the 2018 PolarDB database performance competition to gain a competitive edge.
Conclusion
While Java cannot directly bind threads to CPUs, the OpenHFT Java-Thread-Affinity library offers a practical solution by bridging Java and native OS calls, enabling performance‑critical applications to benefit from CPU affinity.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.