Thread affinity refers to the ability to bind threads to specific CPUs or processor cores in a multi-processor system. By doing so, we can ensure that the threads are always executed on the same processor core, which can improve performance due to cache locality and reduced overhead from migrating threads between cores.
In Java, we can use the Thread class and the ThreadAffinity library to implement thread affinity. Here is an example:
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class ThreadAffinityExample {
private static final Logger LOGGER = LogManager.getLogger(ThreadAffinityExample.class);
public static void main(String[] args) {
ThreadFactory threadFactory = new BasicThreadFactory.Builder()
.namingPattern("example-thread-\%d")
.daemon(true)
.build();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2, threadFactory);
if (SystemUtils.IS\_OS\_LINUX) {
long affinityMask = (1L << 2); // Bind to CPU 2
executor.scheduleAtFixedRate(() -> {
long currentThreadId = Thread.currentThread().getId();
LOGGER.info("Thread {} is running on CPU {}", currentThreadId, ThreadAffinity.getThreadId());
}, 0, 1, TimeUnit.SECONDS);
executor.scheduleAtFixedRate(() -> {
ThreadAffinity.setThreadAffinity(affinityMask);
long currentThreadId = Thread.currentThread().getId();
LOGGER.info("Thread {} is running on CPU {}", currentThreadId, ThreadAffinity.getThreadId());
}, 0, 1, TimeUnit.SECONDS);
} else {
LOGGER.warn("Thread affinity is not supported on this operating system");
}
}
}
In this example, we create a scheduled thread pool executor with two threads, and we use the ThreadAffinity library to bind one of the threads to CPU 2. We then schedule both threads to run at fixed intervals and log their CPU affinity.
Note that thread affinity is only effective if there are enough CPU cores available to support the number of threads being executed. If the number of threads exceeds the number of available CPU cores, some threads will be automatically migrated to other cores by the operating system. Therefore, it is important to monitor the CPU usage and adjust the thread affinity settings accordingly.
Also note that thread affinity is a low-level optimization technique and should only be used after other higher-level techniques, such as reducing contention and optimizing data structures, have been exhausted.