Does Java automatically optimize loops for multi-core processors

A developer told me today that Java (or JIT) can automatically optimize the execution of the for loop, so that it can use all available CPUs on the computer, as long as the code in each iteration of the for loop can be executed without execution, depending on the variables modified in the previous iteration of the loop

Is this an absurd wishful thinking, or is there any truth?

Solution

No, Java won't

This can be verified by writing a useful simple program and checking the number of busy CPU cores

Something like this:

public static void main(String[] args) throws Exception {
    for (int i = 0 ; i < 1000000 ; i++) {
        String s = "this XXX a test".replaceAll("XXX"," is ");
    }
}

When you run this operation, you will see that only one CPU core is used If you want to parallelize such things, you need to use multiple threads, which can be easily done using java 8 stream API or executorservice

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>