RxJava vs Java 8 Parallelism Stream

后端 未结 3 629
春和景丽
春和景丽 2021-02-01 04:33

What are all the similarities and diferences between them, It looks like Java Parallel Stream has some of the element available in RXJava, is that right?

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 04:53

    There is also a difference in threading.

    Stream#parallel splits the sequence into parts, and each part is processed in the separate thread.

    Observable#subscribeOn and Observable#observeOn are both 'move' execution to another thread, but don't split the sequence.

    In other words, for any particular processing stage:

    • parallel Stream may process different elements on different threads
    • Observable will use one thread for the stage

    E. g. we have Observable/Stream of many elements and two processing stages:

    Observable.create(...)
        .observeOn(Schedulers.io())
        .map(x -> stage1(x))
        .observeOn(Schedulers.io())
        .map(y -> stage2(y))
        .forEach(...);
    
    Stream.generate(...)
        .parallel()
        .map(x -> stage1(x))
        .map(y -> stage2(y))
        .forEach(...);
    

    Observable will use no more than 2 additional threads (one per stage), so no two x'es or y's are accessed by different threads. Stream, on the countrary, may span each stage across several threads.

提交回复
热议问题