0

Test environment: MacBook Pro 8-core.

Code

StopWatch stopWatch = new StopWatch();
stopWatch.start();
Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)
    .parallelStream()
    .peek(i -> {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    })
stopWatch.stop();
System.out.println("result = " + stopWatch.getTotalTimeMillis());

In theory, one core allocates one thread. Since we need a total of 9 operations from 1 to 9, we need 9 threads.

That is, since the workload of 8 cores is exceeded, the result should be 2000ms, but 1000ms.

What's even more funny is that when I ran up to 16 threads, I still got 1000ms, and after 17, I got 2000ms. What's wrong?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
paiwmsn
  • 67
  • 1
  • 9
  • Which Macbook exactly do you have? The one with M1 or with an Intel processor? If it's an Intel processor, it has 8 cores, but 16 threads. – dunni Jul 22 '21 at 13:17
  • I'm using intel.. 16 thread is correct! thansks!! :) – paiwmsn Jul 22 '21 at 13:30
  • 1
    Given you use `peek` and do not have a terminal operation, nothing happens: the operation in `peek` is never called! And even if you did have a terminal operation, `peek` is not guaranteed to be called, because some terminal operations allow Java to short-circuit things skipping the pipeline itself. – Mark Rotteveel Jul 22 '21 at 13:56

0 Answers0