Showing posts with label jsr166. Show all posts
Showing posts with label jsr166. Show all posts

Sunday, October 14, 2012

Java 7: Meet the Fork/Join Framework

Free clip art from
http://www.freepik.com
JSR-166(y) is the official name of this new feature which is included in Java 7. If you notice there is a "y" in the name, this is because JSR-166 (Concurrency Utilities) is being added since Java 5, but it wont stop here as there are already plans to add new classes in Java 8 under the JSR-166(e). Check this page maintained by Doug Lea, the creator of JSR-166, for more information.

According to Wikipedia, Parallelism is the "simultaneous execution of some combination of multiple instances of programmed instructions and data on multiple processors" and Java has classes and interfaces to achieve this (sort of...) since DAY 1. You may know them as: java.lang.Thread, java.lang.Runnable, etc... What Concurrency Utilities (java.util.concurrent package) does is simplify the way we code concurrent tasks, so our code is much simpler and cleaner. As developers we haven't had to do anything when running our applications in machines with higher processing resources, obviously, the performance of our applications will improve, but are we really using the processing resources to the maximum? The answer is big NO.

This post will show you how the Fork/Join framework will help us in using the processing resources to the maximum when dealing with problems that can be divided into small problems and all the solutions to each one of those small problems produce the solution of the big problem (like recursion, divide and conquer).

What you need
NetBeans 7+ or any other IDE that supports Java 7
JDK 7+
Blur on an image, example from Oracle

The Basics
The Fork/Join framework focuses on using all the processing resources available in the machine to improve the performance of the applications. It was designed to simplify parallelism in Divide and Conquer algorithms. The magic behind the Fork/Join framework is its work-stealing algorithm in which work threads that are free steal tasks from other busy threads, so all threads are working at all times. Following are the basics you should know in order to start using the framework:
  • Fork means splitting the task into subtasks and work on them.
  • Join means merging the solution of every subtask into one general solution.
  • java.lang.Runtime use this class in order to obtain the number of processors available to the Java virtual machine. Use the method +availableProcessors():int in order to do so.
  • java.util.concurrent.ForkJoinPool Main class of the framework, is the one that implements the work-stealing algorithm and is responsible for running the tasks.
  • java.util.concurrent.ForkJoinTask Abstract class for the tasks that run in a java.util.concurrent.ForkJoinPool. Understand a task as a portion of the whole work, for example, if you need to to do something on an array, one task can work on positions 0 to n/2 and another task can work on positions (n/2) +1 to n-1, where n is the length of the array.
    • java.util.concurrent.RecursiveAction Subclass of the abstract task class, use it when you don't need the task to return a result, for example, when the task works on positions of an array, it doesn't return anything because it worked on the array. The method you should implement in order to do the job is compute():void, notice the void return.
    • java.util.concurrent.RecursiveTask Subclass of the abstract task class, use it when your tasks return a result. For example, when computing Fibonacci numbers, each task must return the number it computed in order to join them and obtain the general solution. The method you should implement in order to do the job is compute():V, where V is the type of return; for the Fibonacci example, V may be java.lang.Integer.

When using the framework, you should define a flag that indicates whether it is necessary to fork/join the tasks or whether you should compute the work directly. For example, when working on an array, you may specify that if the length of the array is bigger than 500_000_000 you should fork/join the tasks, otherwise, the array is small enough to compute directly. In essence, the algorithm you should follow is shown next:

if(the job is small enough)
{
   compute directly
}
else
{
   split the work in two pieces (fork)
   invoke the pieces and join the results (join)
}

OK, too much theory for now, let's review an example.

The Example
Blurring an image requires to work on every pixel of the image. If the image is big enough we are going to have a big array of pixels to work on and so we can use fork/join to work on them and use the processing resources to the maximum. You can download the source code from the Java™ Tutorials site.

Once you download the source code, open NetBeans IDE 7.x and create a new project:



Then select Java Project with Existing Sources from the Java category in the displayed pop-up window:



Select a name and a project folder and click Next >



Now, select the folder where you downloaded the source code for the Blur on an image example:



And select the file ForkBlur.java then click finish:



The source code will be imported and a new project will be created. Notice that the new project is shown with erros, this is because Java 7 is not enable for default:



To fix this, right click on the project name and select the option Properties. On the pop-up dialog, go to Libraries and select JDK 1.7 from the Java Platform ComboBox:



Now, go to the option Sources and select JDK 7 from the Source/Binary Format ComboBox:



Last but not least, increase the memory assigned to the virtual machine when running this application as we'll be accessing a 5 million positions array (or more). Go to the option Run and insert -Xms1024m -Xmx1024m on the VM Options TextBox:


Click OK and your project should be compiling with no errors. Now, we need to find an image bigger enough so we can have a large array to work on. After a while, I found some great images (around 150 MB) from planet Mars, thanks to the curiosity robot, you can download yours from here. Once you download the image, past it on the project's folder.

Before we run the example, we need to modify the source code in order to control when to run it using the Fork/Join framework. In the ForkBlur.java file, go to line 104 in order to change the name of the image that we are going to use:

//Change for the name of the image you pasted 
//on the project's folder.
String filename = "red-tulips.jpg";

Then, replace lines 130 to 136 with the following piece of code:

ForkBlur fb = new ForkBlur(src, 0, src.length, dst);
        boolean computeDirectly = true;

        long startTime = System.currentTimeMillis();
        if (computeDirectly) {
            fb.computeDirectly();
        } else {
            ForkJoinPool pool = new ForkJoinPool();
            pool.invoke(fb);
        }
        long endTime = System.currentTimeMillis();

Notice the computeDirectly flag. When true, we'll NOT be using the fork/Join Framework, instead we will compute the task directly. When false, the fork/join framework will be used.

The compute():void method in the ForkBlur class implements the fork/join algorithm. It's based on the length of the array, when the length of the array is bigger than 10_000, the task will be forked, otherwise, the task will be computed directly.

Following you can see my 2 processors when executing the Blur on an image example without using the Fork/Join framework (computeDirectly = true), it took about 14s to finish the work:



You can see that the processors are working, but not to the maximum. When using the Fork/Join framework (computeDirectly = false) you can see them working at 100% and it took almost 50% less time to finish the work:



This video shows the complete process:




I hope you can see how useful this framework is. Of course, you cannot use it all around your code, but whenever you have a task that can be divided into small tasks then you know who to call.

For more tutorials and information about concurrency in Java, check the Java™ Tutorials site.

see ya!


References:

The Java™ Tutorials. Oracle [online].
Available on Internet: http://docs.oracle.com/javase/tutorial/essential/concurrency/
[accessed on October 10 2012].

PHOTOJOURNAL. NASA Jet Propulsion Laboratory [online].
Available on Internet: http://photojournal.jpl.nasa.gov/catalog/PIA16101
[accessed on October 10 2012].

Tuesday, September 25, 2012

Java 7 conference at UAO - Summary

Hello again. My participation at UAO's event "Día de la Informática y la Multimedia" was a success, I had my talk about Java 7 on Thursday September 20 and it went pretty well. It was a lot of fun, we had about 50-60 assistants, most of them students and some teachers. Few questions were asked at the end of the presentation, I post some of them here giving further explanation:


Q: What happens if there are exceptions when the try with resources automatically calls the close method?
A: The new Interface java.lang.AutoCloseable defines only one method: close():void which throws a java.lang.Exception. So when you define your resources in a try with resources structure, the compiler will warn you about catching the exception. So, whichever exception is thrown during the execution of the close():void method, you will be able to catch it in your try with resources structure.
Something I didn't mention during the presentation, is that there are new methods in the java.lang.Throwable class that allows you to keep track of all the exceptions that were suppressed in order to deliver a specific exception. The methods are:


Q: What about IPv6 support in Java 7?
A: According to this documentation, Java began supporting IPv6 since J2SE 1.4 back in February 2002, but only Solaris and Linux OS were supported. Since version J2SE 1.5 Windows OS is also supported. Even though, there are some considerations you should be aware of if you want your java IPv4 applications running on IPv6, for example:


Q: Any support for 3D?
A: Java 3D is a special API that enables the creation of three-dimensional graphics applications and Internet-based 3D applets. It is not part of the Java SE so you have to download it and add it to your application libraries. For more information about this API, check its official home page.

Q: What else has Java for developers?
A: The Java platform offers a lot to developers, it allows them to build cross-platform applications. "Write once, run everywhere" is a serious thing to Java. It is everywhere from PCs, to TVs, phones, mobile devices, bluerays,  kindles... etc. The features that every release of Java SE offers are the base of the Java platform.


Java 7, 1+ año después
That was the name of my presentation and you can download it using the following link: Download PDF File
More info about the event can be found here (spanish).

See ya!

Saturday, September 22, 2012

Java 7 conference for ASUOC - Summary

Colombia Oracle Users Group
Hello again. My participation at ASUOC's meeting was a success, I had my talk about Java 7 on Thursday September 13, and it went pretty well. It was a lot of fun, we had about 30 assistants on site and 1027 visitors online (according to the streaming stats). Few questions were asked at the end of the presentation, I post some of them here, giving further explanation:

Q: Is there really any difference in performance when migrating if-else structures to switch structures?
A: There are a lot of discussions about this topic, but if you look at the decompiled code, you will notice that a switch with String cases is translated into two switches at compile time. In the first one, every case is an if statement and if there are Strings with the same hash code, then you'll get an if-else-if statement. So what if many of your String objects have the same hash code?... You will get a long (depending in your cases)  if-else-if statement inside a switch statement and then, the performance of the application may not be the best (but not the worst).
Anyway, I think it is hard to get many String objects with the same hash code in a real scenario, this is a good feature and I'm pleased we have it now.

Q: Do you know if there have been issues with applications compiled for previous versions of Java when running in Java 7?
A: There is a list of Deprecated API that you should be aware of, so you don't use it in your code: Java 7 Deprecated API
On the other hand, some companies publish something called "certification matrix" for their products, so you can know if they can work with some technology, like Java 7. For example, Oracle E-Business Suite is not yet certified to be used with Java 7.

Q: Did you make any change to the NIO.2 example in order to run it in Linux OS?
A: The NIO.2 example was the same for Windows OS as for Linux OS. In Java there's a saying "write once, run everywhere" so you can run the same code in a Windows or Linux machine. Nevertheless, you should know that different file systems have different notions about which attributes should be tracked for a file, as noted in the Managing Metadata (File and File Store Attributes) Tutorial.

Java 7, 1+ año después
That was the name of my presentation and you can download it using this link (in spanish): Download PDF File.

The presentation was also recorded but is not uploaded yet. I will update this post as soon as the presentation is available.
Following you will find the links to the conference (spanish, 01:30 aprox.):



See ya!

Wednesday, September 19, 2012

Java 7 conference at UAO

Hello all, continuing with the Java 7 conference series, I've been invited to talk about Java 7 at Universidad Autónoma during its event: "Día de la Informática y la Multimedia", so if you are around and want to learn the new features that Java 7 has for you, please come and join us. I will be presenting Project Coin, NIO.2 and the Fork/Join Framework. Pretty much the same content as the conference at Universidad Icesi last week.

The information of my presentation is as follows:

LanguageSpanish
WhereUniversidad Autónoma
Aulas 4 Torreon 1A
Cali, Colombia
WhenSeptember 20th 2012
14:00 - 15:30 (GMT-5)

More info (in spanish):
Universidad Autonóma

See ya!


Monday, September 10, 2012

Java 7 conference for ASUOC

Colombia Oracle Users Group
Hello all, I'm attending a Colombia Oracle Users Group meeting this week and I'll be speaking at it about Java 7, so if you are around, please come and join us. You can also watch the event via streaming at ASUOC's web site. I will be speaking at the event presenting Project Coin, NIO.2 and the Fork/Join Framework.

The information of my presentation is as follows:

LanguageSpanish
WhereICESI University
Auditorio Varela S.A.
Cali, Colombia
WhenSeptember 13th 2012
16:00 - 17:30 (GMT-5)

More info (in spanish):

Colombia Oracle Users Group
ICESI University

See ya!


Tuesday, May 1, 2012

Java 7 New Features Cookbook Review Part 1

Portada del libro tomada de
http://www.packtpub.com
Wondering what new features Java 7 has for you, but you don't know where to start? Well, in this post I'm going to start my review of the book "Java 7 New Features Cookbook", written by Richard M. Reese and Jennifer L. Reese, and published by PACKT.

By now I have read the first and second chapters of the book and can tell you how easy it is to read and understand the recipes. The recipes are written in the form "Getting ready - How to do it - How it works - There's more..." which allows you to start using the new features very fast and avoid pitfalls.

Looking at the table of contents you realize that the book covers all major improvements done for Java 7:
  • Chapter 1 is dedicated to Project Coin (JSR334), those small changes to the language that as developers, we'll love.
  • Chapters 2, 3, 4, 5 and 6 are deeply dedicated to the new Java IO named NIO.2 (JSR203).
  • Chapter 7 and 8 explain the graphical user interface and event handling improvements.
  • Chapter 9 is about database, security and system enhancements.
  • Chapter 10 is dedicated to the fork/join framework (JSR166).
As you can see, the major improvements of Java 7 (Project Coin, NIO.2 and the fork/join framework) are being covered in this book, that's why I recommend it if you want to upgrade your knowledge of Java to it's latest version.

One more thing, the book is published in a lot of formats: printed book, kindle, PDF, ePub, so you have many options to read it. I have the kindle edition and it looks great on my kindle, paragraphs are well formatted and the source code is easy to read.

For more information about  this book go to:
http://www.packtpub.com/java-7-new-features-cookbook/book

See ya!