Java – why does a single threaded process execute on multiple processors / cores?
Say I run a simple single threaded process, as follows:
public class SirCountALot { public static void main(String[] args) { int count = 0; while (true) { count++; } } }
(this is java because it's familiar to me, but I doubt it's important)
I have an i7 processor (4 cores or 8 count hyper threads) and I am running Windows 7 64 bit, so I started Sysinternals Process Explorer to view CPU usage. As expected, I saw that it was using about 20% of all available CPUs
However, when I switch the options to display 1 graph per CPU, I see that using 1 of the 4 "cores", the CPU usage is all over the core:
Instead, I expect a maximum of one core, but this only happens when I set the affinity of the process to a single core
Why is the workload spread across separate cores? Do not spread the workload of multiple cores, resulting in cache or other performance loss?
Is this a simple reason to prevent a core from overheating? Or is there a deeper reason?
Editor: I know the operating system is responsible for the arrangement, but I want to know why it is "troublesome" From a naive point of view, is it a simpler and more effective way to stick (most *) single threaded processes to a core?
*I mainly talk about single thread, because there are multiple threads, but only two people are doing anything:
Solution
The operating system is responsible for the arrangement You can automatically stop the thread and restart it on another CPU It will do so even if no other machine is doing it
This process moves around the CPU because the operating system does not see reason to continue running threads on the same CPU every time
To this end, I have written a lock thread library to a CPU, so it will not move and will not be interrupted by other threads This reduces latency and improves throughput, but wastes CPU for the thread This applies to Linux, and maybe you can adapt to windows https://github.com/peter-lawrey/Java-Thread-Affinity/wiki/Getting-started