Runtime.availableProcessors: what is it going to return?

后端 未结 3 1955
臣服心动
臣服心动 2020-12-17 23:41

The javadoc for Runtime.availableProcessors() in Java 1.6 is delightfully unspecific. Is it looking just at the hardware configuration, or also at the load? Is

相关标签:
3条回答
  • 2020-12-18 00:14

    On Windows, GetSystemInfo is used and dwNumberOfProcessors from the returned SYSTEM_INFO structure.

    This can be seen from void os::win32::initialize_system_info() and int os::active_processor_count() in os_windows.cpp of the OpenJDK source code.

    dwNumberOfProcessors, from the MSDN documentation says that it reports 'The number of logical processors in the current group', which means that hyperthreading will increase the number of CPUs reported.

    On Linux, os::active_processor_count() uses sysconf:

    int os::active_processor_count() {
      // Linux doesn't yet have a (official) notion of processor sets,
      // so just return the number of online processors.
      int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
      assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
      return online_cpus;
    }
    

    Where _SC_NPROCESSORS_ONLN documentation says 'The number of processors currently online (available).' This is not affected by the affinity of the process, and is also affected by hyperthreading.

    0 讨论(0)
  • AFAIK, it always gives you the total number of available CPUs even those not available for scheduling. I have a library which uses this fact to find reserved cpus. I read the /proc/cpuinfo and the default thread affinity of the process to work out what is available.

    0 讨论(0)
  • 2020-12-18 00:30

    According to Sun Bug 6673124:

    The code for active_processor_count, used by Runtime.availableProcessors() is as follows:

    int os::active_processor_count() {
      int online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
      pid_t pid = getpid();
      psetid_t pset = PS_NONE;
      // Are we running in a processor set?
      if (pset_bind(PS_QUERY, P_PID, pid, &pset) == 0) {
        if (pset != PS_NONE) {
          uint_t pset_cpus;
          // Query number of cpus in processor set
          if (pset_info(pset, NULL, &pset_cpus, NULL) == 0) {
        assert(pset_cpus > 0 && pset_cpus <= online_cpus, "sanity check");
        _processors_online = pset_cpus;
        return pset_cpus;
          }
        }
      }
      // Otherwise return number of online cpus
      return online_cpus;
    }
    

    This particular code may be Solaris-specific. But I would imagine that the behavior would be at least somewhat similar on other platforms.

    0 讨论(0)
提交回复
热议问题