I have a multithreaded program running on a quad-core Intel i7. When I execute Runtime.getRuntime.availableProcessors(), I get 8, and I know that hyperthreading is available on this CPU.
However, when I create threads, my CPU levels are at 100% (i.e. non-zero) for 4 threads, meaning that 4 threads are unused. Is there any way to enable hyperthreading in Java?
解决方案
Hyperthreading is enabled by the fact that all modern JVMs use native threads, thus this is a OS/CPU config setting.
However Hyperthreading does not give you extra cores, it permits fine grained timeshare of the four cpus that you have. That is, while one thread is stalled, say waiting for a page of memory to be flown into the cache then another thread can swoop in and make use of parts of the CPU. It adds about 10% extra to the size of a CPU core due to more complex scheduling requirements and does not benefit all applications.
If you have maxed out the four cpus with four threads, then that is possible with hyperthreading turned on or off. It just means that those threads are running hot, without blocking much.
The reason that Java reports an 8 core CPU, rather than 4 is because the OS tells Java that the CPU has 8 cores. The OS believes that because the OS has been told to schedule threads as though it was an 8 core CPU, this made adding support of hyperthreading to OSes much simpler. The OS carries on managing threads as before, oblivious to much of the inner workings of hyperthreading and lets the CPU manage the low level scheduling of the assembly as and when parts of the cpu become available.
A more detailed discussion, with benchmarks can be read here