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

后端 未结 7 799
臣服心动
臣服心动 2021-01-31 00:07

I\'m new to java multi-threaded programming. The question that has came to my mind is that how many threads can I run according to the number of my CPU

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 00:47

    Don't worry about getting a higher number of threads than CPU cores; that is actually not in your hands, but in OS'.

    Assuming the JVM maps your java threads over OS threads (which is fairly normal these days), it depends on the thread management your OS does. There you rely on how smart the kernel implementation is to get performance out of your cores.

    What you must keep in mind is that your design must be sustainable. For example, application servers are built on a threadpool full of worker threads. Those threads are awaken in order to serve requests. Do you want a thread for each request? Then you will surely have a problem - requests can arrive in the thousands to the server, and that could be a problem for the kernel to manage. Actually the threadpool size should be limited (between 1 and X and easily changed even in real time), threads should get work from a concurrent queue (java gives you some excellent classes for that) and each one attend requests sequentially.

    I hope that being of help

提交回复
热议问题