mercredi 25 novembre 2015

Best way performance wise to use limit on stream in case of multithreading

I watched a talk by José Paumard on InfoQ : http://ift.tt/1OsF0KX (French)

The thing is I got stuck on this one point. To collect 1M Long using stream AND multithreading we can do it this way :

Stream<Long> stream = 
  Stream.generate(() -> ThreadLocalRandom.current().nextLong()) ;

List<Long> list1 = 
  stream.parallel().limit(10_000_000).collect(Collectors.toList()) ;

But given the fact that the threads are always checking the said limit in hinders performance.

In that talk we also see this second solution :

Stream<Long> stream = 
  ThreadLocalRandom.current().longs(10_000_000).mapToObj(Long::new) ;

List<Long> list = 
  stream.parallel().collect(Collectors.toList()) ;

and it seems to be better performance wise.

So here is my question : Why is that the second code better, and is there a better, or at least less costly way to do it?




Aucun commentaire:

Enregistrer un commentaire