A fellow developer told me today that Java (or the JIT) can automatically optimize the execution of a for loop so that it uses all of the available CPUs on the computer, so long as the code in each iteration of the for loop can execute without relying on variables modified in previous iterations of the loop.
Is this outrageous wishful thinking, or is there any truth in it?
No, it doesn't. JVM would have to prove that your for loop body can be safely parallelised and it is a very complex problem.
If you are interested in parallelising some of your logic you might take a look at Java 8 Stream API and its support for parallel streams.
No, Java does not do this.
This can be verified by writing a simple program which does some work, and checking how many CPU cores are busy.
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, you will see that only one CPU core gets used. If you want to parallelize something like this, you need to use multiple threads, which can be done using the Java 8 Stream API or easily with ExecutorService.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With