Search code examples
linuxjvmcpu-cores

Deceive the JVM about the number of available cores (on linux)


In some purpose it is needed to make JVM think about it runs on machine with Ncores on board instead of real number of cores (e.g. 4 cores instead of 16).

JVM runs under some Linux build, based on Mandriva/Red Hat Linux core.

This question is borderline case because I expect various solutions of this problem. This is not pure linux-administration question, and it isn't pure programmer's question.

So... any ideas?


Solution

  • The following Java program prints the number of processors as seen by the Java VM:

    public class AvailableProcessors {
        public static void main(String... args) {
            System.out.println(Runtime.getRuntime().availableProcessors());
        }
    }
    

    If I execute this program on my home computer, it prints 4, which is the actual number of cores (including hyper threading). Now let's trick the Java VM into believing there are only two processors:

    $ echo '0-1' > /tmp/online
    $ mount --bind /tmp/online /sys/devices/system/cpu/online
    

    If I run the above program again, it prints 2 instead of 4.

    This trick affects all processes on your system. However, it's possible to restrict the effect only to certain processes. Each process on Linux can have its own namespace of mount points. See for example the section Pre-process namespaces in the man page of mount(2). You can for example use lxc to start new processes with their own mount namespace.