Does Java optimize for loops for multi-core processors
One developer told me that Java (or JIT) can automatically optimize the execution of a for loop so that it uses all available CPUs on the computer, if the code in each iteration of the for loop can execute without using the variables changed in previous iterations of the loop.
Is this outrageous wishful thinking, or is there some truth to it?
source to share
No, Java doesn't.
This can be verified by writing a simple program that does some work and checks how many processor cores are in use.
Something like that:
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, you will see that only one CPU core is being used. If you want to parallelize something like this you need to use multiple streams, which can be done with the Java 8 Stream API or with ExecutorService
.
source to share
No, it is not. The JVM would have to prove that the body of the loop for
can be safely parallelized, and this is a very difficult problem.
If you are interested in parallelizing some logic, you can take a look at the Java 8 Stream API and concurrent streaming support.
source to share
I'm guessing your guy can reference Fork / Join in Java 7. Please take a look at this: https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
Note that if you look at Java 7/8 features, you will notice that the bulk of the core features are performance and multi-core utilization. e.g. Fork / Join, Parallel Array Sorting (based on Fork and Join) and other functions
source to share
At the moment, it seems that this is actually done. I tested a program that had three perfectly normal nested loops that copied one 2d array to another 2d array 10 times to average the volatility. At runtime, the program scaled to use all the cores on my machine as viewed from the activity monitor. Then I used the time command to measure the CPU and real time of the process and got the following results:
$ time java ArraysTest
real 0m17.562s
user 1m9.429s
sys 0m1.775s
The only way to see that it could use more user time than in real time is if it uses multiple processor cores. From this I must conclude that java has optimized the code by parallelizing it.
source to share