Adam Bien's Weblog

Tuesday Jan 28, 2014

Java 8: From Ordinary For-Loop To An IntStream

Legacy:


for (int i = 0; i < 10; i++) {
	System.out.println(i);
}

Fancy:


IntStream.range(0, 10).forEach(
	nbr -> System.out.println(nbr)
);

Why? ...because the execution of the following snippet takes 1 second and not 10 seconds:


IntStream.range(0, 10).parallel().forEach(
	nbr -> {
	try {
		Thread.sleep(1000);
		} catch (InterruptedException ex) {}
        	System.out.println(nbr);
        }
);


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Comments:

Nitpick mode: it only takes 1 second if you have at least 10 cores...

Posted by Bert-Jan on January 28, 2014 at 02:01 PM CET #

Actually it took 3 seconds to show 2, 7, 8, 6, 4, 1, 9, 5, 3, 0

:)

But I have only four available processors ;)

Fancy and cool anyway

Posted by Javier Beneito Barquero on February 04, 2014 at 08:02 PM CET #

Actually it took 3 seconds to show an unordered randomly list :)

But I have only four available processors ;)

Fancy and cool anyway

Posted by 94.126.240.3 on February 04, 2014 at 08:03 PM CET #

@Bert-Jan: I dont think this is right.
Thread.sleep() does not perform busy waiting, so all Threads will wait ~1 second in parallel. With one core System.out.println() will be executed sequentially in an order determined by the Scheduler.

Posted by gustav on February 05, 2014 at 03:26 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
...the last 150 posts
...the last 10 comments
Links
License