Java – How to set a Java thread’s cpu core affinity

javalinux

I searched previous postings on the similar topic but could not find a befitting answer therefore asking this question. Your help in answering it is highly appreciated.

I am aware of setting a process's affinity to a particular CPU core by taskset command in Linux. But I want to set a Java thread's affinity to a particular cpu core so that other threads belonging to the same process can run on all remaining cores. For example if I have a process containing 10 threads with 4-core machine, I would like to reserve core-1 for a thread and let remaining 9 threads run on remaining 3-cores. Can it be done and how?

Thanks
Sachin

Best Answer

Say 2241 is the pid of your java process. Run:

jstack 2241

This gives you a list of threads. Find yours there and note the nid field. Say nid=0x8e9, which converts to base 10 as 2281. Then run:

taskset -p -c 0 2281

Done.