Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Multithreading - Assign threads to processor cores

I am writing an application in java which involves parallel computing. My question is how can I explicitly assign threads to cores? What is the programming logic for it?


Can anyone tell why class Executor is used? Thanks

like image 848
KLCoder Avatar asked May 04 '11 06:05

KLCoder


People also ask

How are threads assigned to cores?

Thread allocation is managed by the operating system. Threads are created using OS system calls and, if the process happens to run on a multi-core processor, the OS automatically tries to allocate / schedule different threads on different cores. Thread allocation is managed by the programming language implementation.

Do Java threads run on different cores?

Java will benefit from multiple cores, if the OS distribute threads over the available processors. JVM itself do not do anything special to get its threads scheduled evenly across multiple cores.

Can a developer assign a thread execution to a particular core?

you can use GOMP_CPU_AFFINITY variable and set which thread to use which CPU core. For example, if you have 16 cores, and use only 4 threads, you can set to execute to cores 0-3, or 0, 4, 8, 12.

Do threads share CPU cores?

A core provides one or more threads. However, if a CPU core exposes multiple threads (typically only 2), the expectation is that the threads do contend with each other for execution resources. The idea with multi-threaded cores (commonly called hyperthreading) is that cores have lots of execution resources.


2 Answers

You cannot assign threads to cores.

  1. Java7's fork/join framework addresses exactly the same problem. Automatically though (It will be designed for multi-core processors).

  2. What you can do is to set Thread priority to prioritize your threads, if that's what you want to achieve.

  3. JNI might be another direction to export, but an overkill I guess. You can look at Peter Lawrey's Java-Thread-Affinity which uses JNI (I haven't used it).

like image 187
zengr Avatar answered Oct 19 '22 22:10

zengr


I think the simple answer here would be you just can't.

like image 23
Jan Zyka Avatar answered Oct 19 '22 22:10

Jan Zyka