09. Java8-流式API-并行流

x33g5p2x  于2021-12-18 转载在 其他  
字(5.8k)|赞(0)|评价(0)|浏览(334)

Java8 中流的处理可以方便地在并行和串行之间切换, 并行流底层采用的是java7 特性fork/join 框架. 虽然并行流透明地使用了多线程, 但也并不是说是完美的, 并不能适合于所有场景. 并行流适用于单次运算时间较长的情景,而不适用于单次运算时间较短的场景. 此外并行流会占用更多的cpu 资源和内存.

  • fork/join 拆分子任务是耗时的, 对于本身并不复杂的运算, 使用并行流效率反而并没有使用串行流效率高
  • 并行流中多线程的数量等于服务器的处理器数量, 并非不能修改, 但是一个全局变量, 修改的话会对所有的并行流进行修改, 并不能对某个并行流指定这个值
  • 并行流会充分利用服务器的资源, 在进行大量计算时, 会瞬间占用cpu 大量的资源.笔者在进行测试的时候, 就出现了cpu 瞬间飙升至90%+, 且内存溢出这个异常.

1. 相关API

默认情况下为串行流, 即单线程.

API 签名描述
S parallel()将串行流转换为并行流
S sequential()将并行流转换为串行流

2. 正确的测试用例

当拆分任务时间小于计算单次运算时间时, 并行流性能很难超过串行流, 所以进行测试时, 单次运算时间需要设置较长.

  • 测试用例:
/** * @Description: 并行流测试 * @author: zongf * @date: 2018-07-01 11:07 */
public class TestParallel {

    public static Long handleService(Long l){
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return l;
    }

    // 测试串行流性能
    @Test
    public void test_sequential(){

        long start = System.nanoTime();

        LongStream.range(0, 10).sequential().map(TestParallel::handleService).count();

        Long end = System.nanoTime();

        System.out.println("cost:" + (end -start)/1_000_000);
    }

    // 测试并行流性能
    @Test
    public void test_parallel(){

        long start = System.nanoTime();

        LongStream.range(0, 10).parallel().map(TestParallel::handleService).count();

        Long end = System.nanoTime();

        System.out.println("cost:" + (end -start)/1_000_000);

    }

}
  • 测试结果:
main
main
main
main
main
main
main
main
main
main
cost:10082
main
ForkJoinPool.commonPool-worker-1
ForkJoinPool.commonPool-worker-2
ForkJoinPool.commonPool-worker-3
ForkJoinPool.commonPool-worker-1
main
ForkJoinPool.commonPool-worker-2
ForkJoinPool.commonPool-worker-3
ForkJoinPool.commonPool-worker-1
main
cost:3015

3. 错误的测试用例

通过以下测试用例,笔者并未成功测出并行流性能优于串行流, 反而测出了内存溢出的异常. 因为拆分子任务时间较长, 超过计算时间, 所以并行流优势并不明显. https://www.oschina.net/question/1865616_2282449

  • 测试用例
package org.zongf.learn.java8.stream;

import org.junit.Test;

import java.util.stream.Stream;

/**
 * @Description: 并行流测试
 * @author: zongf
 * @date: 2018-07-01 11:07
 */
public class TestParallel {

    Long endNum = 50_000_000l;

    // 测试串行流性能
    @Test
    public void test_sequential(){

        long start = System.nanoTime();

        Long sum = Stream.iterate(0L, (x) -> x + 1)
                .limit(endNum)
                .sequential()
                .reduce(0L, Long::sum);

        Long end = System.nanoTime();

        System.out.println("cost:" + (end -start)/1_000_000);
    }

    // 测试并行流性能
    @Test
    public void test_parallel(){

        long start = System.nanoTime();

        Long sum = Stream
                .iterate(0L, (x) -> x + 1)
                .limit(endNum)
                .parallel()
                .reduce(0L, Long::sum);

        Long end = System.nanoTime();

        System.out.println("cost:" + (end -start)/1_000_000);

    }

}
  • 测试结果:笔者并未能成测试出并行流快于串行流, 当笔者继续加大endNum 的值时, 很无情地排除了内存移除异常,任由笔者如何跳转jvm 内存参数都不能解决.
java.lang.OutOfMemoryError
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:598)
	at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
	at java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:735)
	at java.util.stream.SliceOps$1.opEvaluateParallelLazy(SliceOps.java:155)
	at java.util.stream.AbstractPipeline.sourceSpliterator(AbstractPipeline.java:431)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233)
	at java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:474)
	at org.zongf.learn.java8.stream.TestParallel.test_parallel(TestParallel.java:39)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
	at java.lang.Long.valueOf(Long.java:840)
	at org.zongf.learn.java8.stream.TestParallel.lambda$test_parallel$1(TestParallel.java:36)
	at org.zongf.learn.java8.stream.TestParallel$$Lambda$1/1068824137.apply(Unknown Source)
	at java.util.stream.Stream$1.next(Stream.java:1033)
	at java.util.Spliterators$IteratorSpliterator.trySplit(Spliterators.java:1784)
	at java.util.stream.AbstractShortCircuitTask.compute(AbstractShortCircuitTask.java:114)
	at java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:731)
	at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
	at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
	at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
	at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

相关文章