Search code examples
javamultithreadingoperating-systemmulticore

What situations do single core threading beat threads across cores


Im trying to find real world examples where there might be more advantages to running threads on a single core vs spanning multiple cores.

Is there a cost to spawning threads across cores vs spawning in the same core.

How does java (or the os) determine when to allocate work on specific cores.

Finally, is there a way to specify explicitly that threads should run on a specific core or is this os level determined?


Solution

  • If the logic is CPU bound, you only want a single thread per core because multiple CPU bound threads on the same core lead to waste due to context switching, cold caches etc. If the thread isn't CPU bound, but I/O bound, it could be beneficial to use multiple threads per core. But this depends on the architecture, e.g. in thread per core architectures like Seastar/Scylla, you still want a single thread per core.

    Java doesn't do anything to determine how threads get mapped to cores. That is a task of the OS since Java threads are tied to a native thread.

    In Java, there is no out-of-the-box solution to pin threads to cores. But you can use taskset for that or use one of Peter Lawrey's libraries:

    https://github.com/OpenHFT/Java-Thread-Affinity