简体   繁体   中英

Java - Non Parallel code using multiple CPUs

The below code is non-parallel. Monitoring Resource Monitor, I would see that all my cores would evenly distribute the task.

import java.math.*;
import java.util.stream.*;

public class Main {
    public static BigInteger factorial(int number) {
        if(number <= 1) {
            return BigInteger.valueOf(1);
        }
        return BigInteger.valueOf(number).multiply(factorial(number-1));
    }

    public static void main(String[] args){
        IntStream.range(1, 5000).forEach(Main::factorial);
    }
}

When I made the task parallel, changing:

IntStream.range(1, 5000).forEach(Main::factorial);

to:

IntStream.range(1, 5000).parallel().forEach(Main::factorial); 

Again I would see all the cores being used (only this time, all my cores would have 100% usage). I can explain away the capping of the cores due to my processor being from the stone ages (Core 2 Quad), but I can't explain how the sequential task also uses multiple cores.

Sequential computation is performed in the single OS thread, but OS threads are not bound to particular CPU core and OS may decide to move the thread from one core to another (a so-called thread migration). You may bind the thread or process to the particular core setting the thread affinity (this depends on the OS you are using).

it can be any daemon threads which are running during your application (in your JVM), for example Garbage Collector. It runs in separate thread and cleans objects which are not in use. So GC works in different thread and consumes your CPU.

So, even if you have single thread application, java starts some of its services which works in background in different threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM