2

I am working on a PC with an Intel Core i5 processor which reports to have 12 processors, which I believe is comprised of 6 cores each with two threads.

I have done some research and it appears that Java uses kernel threading. I need to dramatically increase the performance of an existing Java program and am hoping I can use all 12 of the core i5 threads to do this.

I am trying to use the IntStream().parallel.forEach() Java 1.8 feature which looks like I can parallelize nested for() loops with as many threads as available.

My concern is: whether my code can use all twelve threads or just the two threads on one core?

catch23
  • 17,519
  • 42
  • 144
  • 217
cnash
  • 23
  • 3
  • 1
    It should use all the cores. Why don't you print `Thread.currentThread().getName()`? – shmosel May 02 '22 at 20:51
  • 1
    Hi, this isn't a good question here because it's not clear what your specific problem is. Could you maybe rephrase in a way that states your expectations and your differing results? – Ian Newson May 02 '22 at 20:54
  • Whether your CPU uses [hyper-threading](https://en.wikipedia.org/wiki/Hyper-threading) or not is transparent to the [JVM](https://en.wikipedia.org/wiki/Java_virtual_machine). A 6-core CPU with hyper-threading will present as 12-cores to the JVM. Your Java app does not know, nor does it care, if those 12 cores are physical/real or logical/virtual. – Basil Bourque May 03 '22 at 08:35

2 Answers2

2

For knowing how many processors you could use at your machine you could use availableProcessors(), snippet from java doc:

Returns the number of processors available to the Java virtual machine. This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately

Code:

public class CoresDemo {
    public static void main(String[] args) {
        int nCores = Runtime.getRuntime().availableProcessors();
        System.out.println(nCores);
    }
}
catch23
  • 17,519
  • 42
  • 144
  • 217
1

Java parallel stream uses ForkJoinPool.commonPool; which calculates total threads by Runtime.getRuntime().availableProcessors() - 1 (this is for leaving one processor calling thread).

So in your case it would be 12 -1 = 11 processors.

So you might be able to use 11 threads for your multithreading operations.

E.g. on my system I do have 8 available processors & I can see below operations is being performed by 7 threads:

System.out.println(Runtime.getRuntime().availableProcessors());
        IntStream.range(0, 1000000).parallel()
                .forEach(value -> System.out.println(value + "  " + Thread.currentThread().getName()));
Ashish Patil
  • 4,428
  • 1
  • 15
  • 36