0

I'm reading the book "Mastering Lambdas: Java Programming in a Multicore World". It has simple example of collecting stream of books to list :

List<Book> bookList = libraryStream.collect(Collectors.toList());

And I quote from the book:

the stream operations can be safely executed in parallel, even if the List into which the stream elements are accumulated (ArrayList is used in the current implementation) is not threadsafe.

I don't understand how it can be thread safe after the returned list it modified from multiple thread if collecting using parallel stream.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user1409534
  • 2,140
  • 4
  • 27
  • 33
  • http://stackoverflow.com/questions/22350288/parallel-streams-collectors-and-thread-safety: Brian Goetz, Java Language Architect provides a good answer – Jean Logeart Jul 03 '15 at 04:24
  • The list is not modified from different threads. Several lists are created instead and they are finally merged together. – Tagir Valeev Jul 03 '15 at 04:32
  • The _result_ can't be thread-safely modified, but `Collections.toList()` internally does the right thing even if it's working in parallel. – Louis Wasserman Jul 03 '15 at 04:33
  • During reduce operation in parallel, the stream is split and then merged. So yes it can work in parallel without side affects. – Ramandeep Nanda Jul 06 '15 at 18:22

0 Answers0