开发者

Callable code won't use more than one CPU with ThreadPoolExecutor

开发者 https://www.devze.com 2023-03-22 07:02 出处:网络
I have a quad core processor and the ThreadPoolExecutor is set to 4 core threads, but when I submit my callables (hundred or so) to the ThreadPoolExecutor, Java never uses more than 25% CPU.开发者_如何

I have a quad core processor and the ThreadPoolExecutor is set to 4 core threads, but when I submit my callables (hundred or so) to the ThreadPoolExecutor, Java never uses more than 25% CPU.开发者_如何学编程 Why does it not use all of them?

Code in question:

static class Sum implements Callable{
    private double bigarray[];
    public Sum(double [] bigarray){
        this.bigarray = bigarray;
    }
    @Override
    public Double call(){
        double sum = 0;
        for (int i = 0; i < bigarray.length; i++){
            sum += bigarray[i];
        }
        return sum;
    }
}


You can try to see how many CPUs are available to your java program by calling Runtime.getRuntime().availableProcessors(). The platform you are running on may be restricting you to only use one CPU (if you are running your program in a virtual environment for example).


In general, currently there is no interface in Java to control cores and processors affinity so your code (and threads) is scheduled by OS as it finds right. You might not like it. As it was said well Running multiple threads on multiple CPU cores?

In general that is not a job for the JVM; it is the OS that allocates a core for a thread, the JVM is just a program. If you're running this on an MS Windows machine you can try to set the 'affinity' for the JVM, i.e. tell the scheduler (task manager) what CPUs (cores) the JVM is allowed to use.

But I do not think this is a way to go.

See the answer to Stack Overflow question How does Java makes use of multiple cores?.

0

精彩评论

暂无评论...
验证码 换一张
取 消