• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Streams parallel operation resulting in a serial like operation

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I am a bit puzzle with the next code derived from the sybex OCP study guide:



while addValues returns an undedictable result, addValues2 always returns a nice sorted list.
How come? Is addValues2 not executed in parallel? And if it is in parallel, what kind of sorcery is this that allows parallel operations ending in a sorted list?

Thanks in advance for any clarification
 
Master Rancher
Posts: 5060
81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, the basic reason is that the people who coded collect() and Collectors.toList() were smart enough to find a way to ensure that the operation could get the correct result even if you use multiple threads.   That's true of the other collectors defined in the Collectors class too.  That's one of the reasons we like to use those classes.

In this particular case, you can imagine that if you split the work among just two threads, the thing to do would be to divide the work into two halves, in a way that you could combine the results later.  If the original IntStream is supposed to go from 1-11, then maybe one thread will do 1-6 and the other will do 7-11.  Both threads filter out the odd numbers.  And the first thread will make a List of 2,4.  And the second thread makes a List of 6,8,10.  And when both threads have finished that wok, then the two lists are combined into one List, knowing that the list from the first thread comes first, and the list from the second list comes second.  So you get a list of 2,4,6,8,10.

Now in practice, there may be more than two threads.  Or less, if the job is really short.  . But the principle is the same.  Divide the work up, but make sure you do it in a way that you can recover the original order later.
 
He does not suffer fools gladly. But this tiny ad does:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic