2

The following code works and produces a String that is a result of concatenating first 100 unicode characters starting from 1. [I'm working on 1.8 version of Java]

Stream<Character> chars = Stream.iterate('1', op -> (char)(op + 1));
        StringBuilder value = chars.limit(100).reduce
                (new StringBuilder(""), (s, c) -> s.append(c), (p,d) -> p.append(d) );
        System.out.println(value.toString());

Output of the above is --

123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~?????????????????????

But when I make chars a parallel stream as follows, I get an IndexOutOfBoundsException --

        Stream<Character> chars = Stream.iterate('1', op -> (char)(op + 1));
        StringBuilder value = chars.parallel().limit(100).reduce
                (new StringBuilder(""), (s, c) -> s.append(c), (p,d) -> p.append(d) );
        System.out.println(value.toString());

I expected that the order of the characters in the value string would be different since this is a parallel stream but the program would work even for a parallel stream if order did not matter. But I'm getting an IndexOutOfBoundsException. Why am I getting the IndexOutOfBoundsException if make my stream parallel.

Chan
  • 651
  • 2
  • 8
  • 14

1 Answers1

-1

Its because of arrays length and parallel stream functioning. Parallel stream divides the array in multiple chunks and sends them in different cores of cpu to process. This is where such exception is expected.

And can you post the exception trace.

  • And can you post the exception trace – shubhendra sen Sep 25 '19 at 19:04
  • I'm not able to understand. If the stream has 100 elements, the resultant is 100 characters distributed in arrays or whatever is lower level detail sent to different CPU cores? should it increase or decrease the number of elements in the stream? – Chan Sep 25 '19 at 19:04