Java thread affinity

2019-01-01 08:51发布

Does anybody know of a way to lock down individual threads within a Java process to specific CPU cores (on Linux)? I've done this in C, but can't find how to do this in Java. My instincts are that this will require a JNI call, but I was hoping someone here might have some insight or might have done it before.

Thanks!

5条回答
泛滥B
2楼-- · 2019-01-01 09:06

It's not possible (at least with plain Java).

You can use thread pools to limit the amount of threads (and therefore cores) used for different types of work, but there is no way to specify a core to use.

There is even the (small) possibility that your Java runtime doesn't support native threading for your OS or hardware. In this case, green threads are used and only one core will be used for the whole JVM.

查看更多
泪湿衣
3楼-- · 2019-01-01 09:18

IMO, this will not be possible unless you use native calls. JVM is supposed to be platform independent, any system calls done to achieve this will not result in a portable code.

查看更多
初与友歌
4楼-- · 2019-01-01 09:19

I know it's been a while, but if anyone comes across this thread, here's how I solved this problem. I wrote a script that would do the following:

  1. "jstack -l "
  2. Take the results, find the "nid"'s of the threads I want to manually lock down to cores.
  3. Taskset those threads.
查看更多
闭嘴吧你
5楼-- · 2019-01-01 09:22

You can't do this in pure java. But if you really need it -- you can use JNI to call native code which do the job. This is the place to start with:

http://ovatman.blogspot.com/2010/02/using-java-jni-to-set-thread-affinity.html

http://blog.toadhead.net/index.php/2011/01/22/cputhread-affinity-in-java/

UPD: After some thinking, I've decided to create my own class for this: ThreadAffinity.java It's JNA-based, and very simple -- so, if you want to use it in production, may be you should spent some time making it more stable, but for benchmarking and testing it works well as is.

UPD 2: There is another library for working with thread affinity in java. It uses same method as previously noted, but has another interface

查看更多
登录 后发表回答