parallelStream ()
can make Java programs 10 times faster
Main.java
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<Integer> n1 = new ArrayList<>();
List<Integer> n2 = new ArrayList<>();
for(int i = 0; i < 500; i++) {
n1.add(i);
n2.add(i);
}
long s1 = System.currentTimeMillis();
n1.stream().forEach(i -> { try { Thread.sleep(10); } catch(Exception e) { e.printStackTrace(); } });
long t1 = System.currentTimeMillis();
long s2 = System.currentTimeMillis();
n2.parallelStream().forEach(i -> { try { Thread.sleep(10); } catch(Exception e) { e.printStackTrace(); } });
long t2 = System.currentTimeMillis();
System.out.printf("n1 exec time: %d [ms]\n", t1 - s1);
System.out.printf("n2 exec time: %d [ms]\n", t2 - s2);
}
}
There are not many points to collect and explain. n1
is a sequential stream and n2
is a parallel stream calling Thread.sleep (10)
500 times. The reason for try-catch is to handle the checked exception of Thread.sleep ()
. ʻI in
forEach` disappears in the void.
n1 exec time: 5298 [ms]
n2 exec time: 505 [ms]
n2
is more than 10 times faster than n1
!
For n1
, the result of 10ms x 500 times is clearly shown.
According to the Official Documentation (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ForkJoinPool.html), the default number of parallel threads is , It seems to be equal to the number of processors available in the computer.
For applications that require separate or custom pools, a ForkJoinPool may be constructed with a given target parallelism level; by default, equal to the number of available processors.
Looking at the fact that the execution time in the parallel stream is less than 1/10 of that in the sequential stream, it seems that the number of logical processors is applied as the default value instead of the number of physical processors. "It will be 10 times faster" ... Oma Tamaki Isn't it! !! I think that there is a very reasonable tsukkomi, but I think that most recent PCs have about 8 logical processors, so please forgive me.
Basically, you should not update or delete the objects that are commonly referenced in each thread (such as add to List).
Recommended Posts