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?
CodePudding user response:
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);
}
}
CodePudding user response:
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()));