0% found this document useful (0 votes)
2 views

Parallel Streams

Parallel streams in Java allow for concurrent processing of elements by splitting the stream into sub-streams, each handled by its own thread. The methods parallel() and parallelStream() can be used to create parallel streams from sequential ones. Caution is advised when order matters, as the completion order of threads may affect the final result.

Uploaded by

srrm.nnn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Parallel Streams

Parallel streams in Java allow for concurrent processing of elements by splitting the stream into sub-streams, each handled by its own thread. The methods parallel() and parallelStream() can be used to create parallel streams from sequential ones. Caution is advised when order matters, as the completion order of threads may affect the final result.

Uploaded by

srrm.nnn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Streams

Parallel Streams

Copyright © Seán Kennedy


Parallel Streams
• All of the streams thus far have been sequential streams i.e.
the streams have processed the data one element at a time.

• Parallel streams can process elements in a stream


concurrently i.e. at the same time.

• Java achieves this by splitting the stream up into sub-


streams and then the pipeline operations are performed on
the sub-streams concurrently (each sub-stream has its own
thread).

Copyright © Seán Kennedy


Parallel Streams

• To make a stream parallel, we can use the parallel() or


parallelStream() methods.

• parallel() is available in Stream<T>.

• parallelStream() is defined in the Collection<E> interface

Copyright © Seán Kennedy


Parallel Streams

Collection<E>

Stream<T>

Copyright © Seán Kennedy


Parallel Streams
• Firstly, let’s look at a sequential stream that sums up a
stream of numbers.
Sequential stream

Copyright © Seán Kennedy


Parallel Streams

Parallel stream

Copyright © Seán Kennedy


Parallel Streams
• What is happening in the background?

Copyright © Seán Kennedy


Parallel Streams
• Be careful if order is important, as the order of thread
completion will determine the final result (not the order in the
original collection).

Copyright © Seán Kennedy

You might also like