WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java Concurrency Β· Guru Β· question 85 of 100

Can you explain the concept of thread affinity in Java and how it can be used to improve performance?

πŸ“• Buy this interview preparation book: 100 Java Concurrency questions & answers β€” PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Concurrency interview β€” then scores it.
πŸ“ž Practice Java Concurrency β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Java Concurrency questions & answers β€” PDF + EPUB for $5

All 100 Java Concurrency questions Β· All topics