Thursday 25 September 2014

Speeding up Java code execution using parallel execution

Disclaimer note: I am a C# programmer and only have some work experience with Java. The new features of Java 8 makes me as a code much more enthustiastic to this language, since parallel programming, functional programming and collection handling now is much better! In Java, using the Stream Api makes parallel computing easily accessible. Consider this simple code:

import java.io.*; 
import java.util.*; 
import java.util.stream.Stream;

public class FileTest {

 public static void processFile(File file){
  try {
         Thread.sleep(100 + (int)(Math.random()*2000));
         System.out.println(file.getAbsolutePath());
  }
  catch (Exception ex){
   System.out.println(file); 
  }
 }
 
 public static void main(String[] args){
  
  File currentDir = new File("."); 
  File[] children = currentDir.listFiles(); 

  Stream.of(children).forEach(
   file -> processFile(file)); 

 }
}

To speed up the execution of this simple code, just add parallel() before the .forEach:

import java.io.*; 
import java.util.*; 
import java.util.stream.Stream;

public class FileTest {

 public static void processFile(File file){
  try {
         Thread.sleep(100 + (int)(Math.random()*2000));
         System.out.println(file.getAbsolutePath());
  }
  catch (Exception ex){
   System.out.println(file); 
  }
 }
 
 public static void main(String[] args){
  
  File currentDir = new File("."); 
  File[] children = currentDir.listFiles(); 

  Stream.of(children).parallel().forEach(
   file -> processFile(file)); 

 }
}

All these features makes Java 8 a much more attractive language again, and definately more C# developers will look more into Java soon! :-) Some images from Sublime Text 3, which I use to compile and run the code above!
Share this article on LinkedIn.

No comments:

Post a Comment