I'm trying to create 100k virtual threads with simple print statements. When I use the below code, the estimated execution time is 2 milliseconds:
List < Thread > threads = IntStream.of(0, 100000)
.mapToObj(it -> Thread.ofVirtual().unstarted(() -> System.out.println(Thread.currentThread())))
.toList();
long begin = System.currentTimeMillis();
threads.forEach(Thread::start);
for (Thread thread: threads) {
thread.join();
}
long end = System.currentTimeMillis();
System.out.println("time taken: " + (end - begin) + " milliseconds");
But, when I use a for
loop instead of IntStream
, the estimated execution time is 6925 milliseconds.
List < Thread > threads = new ArrayList < > ();
for (int i = 0; i < 100000; i++) {
threads.add(Thread.ofVirtual().unstarted(() -> System.out.println(Thread.currentThread())));
}
long begin = System.currentTimeMillis();
threads.forEach(Thread::start);
for (Thread thread: threads) {
thread.join();
}
long end = System.currentTimeMillis();
System.out.println("time taken: " + (end - begin) + " milliseconds");
I know that IntStream
is more memory efficient than regular for
loops. But, as per my understanding, IntStream
doesn't do anything magical compared to a for
loop.
So, I'm wondering why there's a big gap in the performance above. I'm running this experiment in an 8 core Mac machine.
Update:
IntStream.of()
takes only two numbers above and those are not the range of numbers. So, it is incorrect.
I removed the print statements and used a HashSet
to track the number of platform threads used. After making the corrections, the estimated execution time to create 100k virtual threads using both for
loop and IntStream.range()
is around 150 milliseconds in my 8 core system.
Adding print
statements added lot of overheads as you can see from previously shared results.