how to make Java use all CPU power on a machine?

2020-07-23 01:04发布

问题:

I sometimes write code in Java, and I noticed that sometimes it uses more than 100% CPU on a multicore machine. I am now running some code on a multicore machine that has 33 CPUs (Amazon's EC2), and I want to make my Java process use all CPUs available, so that it will have very high utilization of the machine. Is that possible, or is it left up to Java to decide when to use more than 100% CPU? I do not wish to change the code to use multithreading.

回答1:

Without using multiple threads or processes (or something other than the one process running), you won't be able to achieve n*100% usage on a n-core machine.

The operating system decides to run each of your user programs on a single thread, unless a request for more is made. Without that request, the OS will happily let you run your code in a single thread, potentially maxing out an entire CPU's cycles - but it leaves the others open.



回答2:

If your program is not explicitly multi threaded (you don't start any thread yourself) then the only reason why it can utilize more than one core is because you are using some functionality of a library which ends up delegating work to a thread pool. Apparently you do not have much control over that so you can't make it work more necessarily.

In regards to utilizing all the CPUs in your S3 instance: You could start your program multiple times (e.g. 33 times if you have 33 CPUs). If that is not possible you will have to find out which part of your processing creates work on the thread pool and change your program so it does more of that (in parallel).



标签: java cpu