What is the relationship between number of CPU cores and number of threads in an app in java? What is the relationship between number of CPU cores and number of threads in an app in java? multithreading multithreading

What is the relationship between number of CPU cores and number of threads in an app in java?


The number of threads a system can execute simultaneously is (of course) identical to the number of cores in the system.

The number of threads that can exist on the system is limited by the available memory (each thread requires a stack and a structure used by the OS to manage the thread), and possibly there is a limitation how many threads the OS allows (this depends on the OS architecture, some OS' may use a fixed size table and once its full no more threads can be created).

Commonly, todays computers can handle hundreds to thousands of threads.

The reason why more threads are used than cores exist in the system is: Most threads will inevitably spend much of their time waiting for some event (example: word processor waiting for user to type on keyboard). The OS manages it that threads that wait in such a manner do not consume CPU time.


Idea behind it is don't let your CPU sleep, neither load it too much that it waste most of time in thread switching.

Its helpful to check Tuning the pool size, In IBMs paper

Idea behind is, it depends on the nature of task, if its all in-memory computation tasks you can use N+1 threads (N numbers of cores (included hyper threading)).

Or

we need to do the application profiling and find out waiting time (WT) , service time (ST) for a typical request and approximately N*(1+WT/ST) number of optimal threads we can have, considering 100% utilization of CPU.


That depends on what the threads are doing. The CPU is only able to do X things at once, where X is the number of cores it has. That means X threads at most can be active at any one time - however the other threads can wait their turn and the CPU will process them at appropriate moments.

You should also consider that a lot of the time threads are waiting for a response, or waiting for data to load, or a network message to arrive, etc so are not actually trying to do anything. These idle/waiting threads have very little load on the system.