Showing posts with label jsr334. Show all posts
Showing posts with label jsr334. Show all posts

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!


Friday, June 29, 2012

Campus Party Colombia 2012 - CPCO5 - Second Part

Hello again. My first participation in Campus Party Colombia 2012 is over, I had my talk about Java 7 yesterday,  Thursday June 29, and it went pretty well. It was a lot of fun and networking, not like the Java One though, but there were so many things to see rather than just conferences about technology. There were gaming contests, programming contests, robots exhibitions, music, etc..

I liked it that conferences are not given in rooms, but in open spaces, so assistants can stop and listen to you. I also enjoyed surfing the web at 16 mbs... nice! There were three great speakers that day: Jon Hall Maddog (yes... the Executive Director of Linux International... omg!), Andrés Velásquez (computers CSI) and, of course... ME!!

Some things to improve in the logistics, I missed the way JavaOne (Oracle) treats speakers with food/drinks and spaces to interact with each other, but in the end, it was a lot of fun, I'm not sure how the asistants can stay the whole week in the arena... camping with temperatures of 50-60 °F, but I can say they don't sleep a lot with those fights in starcraft or many other video games.


Y tú ¿ya Javas 7?
That's the name of my presentation and you can download it using this link: Download PDF File
The presentation is also recorded and uploaded at YouTube (in spanish):



I also took some pictures:



Official Information
If you are looking for official information about Campus Party Colombia CPCO5, check the following links:
Official pics of the event 
Official web site of the event

see ya!!

Tuesday, June 26, 2012

Campus Party Colombia 2012 - CPCO5

Hello all, Campus Party Colombia (#CPCO5) is ON!! and I'm having a Java 7 presentation at this event, so if you are around, please come and join us. I will be speaking at the event presenting the Colombia Java Users Group and talking about Project Coin and NIO.2.

The information of my presentation is as follows:

LanguageSpanish
WhereCorferias
Innovation/Development Section
Bogotá, Colombia
WhenJune 28th 2012
9pm-10pm (GMT-5)

More info (in spanish):

Colombia Java Users Group official web site
Campus Party Colombia

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!

Tuesday, January 31, 2012

Java 7 - Project Coin Decompiled Part II

Hello everybody, this is the second part of Java 7 - Project Coin Decompiled, as you remember, we have already seen some of the small changes introduced by Project Coin in Java 7. In this post, we are going to decompile those examples from the last post in order to see what's the compiler doing for us.


What you need
NetBeans 7+ or any other IDE that supports Java 7
Diamond Operator
This is the example of diamond operator we just saw in the last post:

//suppose the classes Region, Country, City and Customer exist
import java.util.*;
...
Map<Region,Map<Country,Map<City,List<Customer>>>> map = new HashMap<>();
...

Now, let's see what's the generated code by the compiler looks like:

import java.util.*;
...
java.util.Map map = new HashMap();
...

Just an old school map definition and instantiation... Why? Because that's how generics works:

When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

It means that the compiler will check during compile time if you are using the correct classes and it will add any necessary cast to the generated class. For example:

//suppose the classes Region, Country, City and Customer exist
import java.util.*;
...
Map<Region,Map<Country,Map<City,List<Customer>>>> map = new HashMap<>();
Map<Country,Map<City,List<Customer>>> m = map.get(new Region());
...

You will get something like this:

//suppose the class Region exists
import java.util.*;
...
Map map = new HashMap();
Map m = (Map)map.get(new Region()); //the compiler added the cast
...


Strings in Switch
Remember the Strings in switch example presented in the last post:

//in a class
...
public void stringToNumber(String str)
{
   switch(str)
   {
      case "one":
         System.out.println(1);
         break;
      case "two":   
         System.out.println(2);
         break;   
      case "three":
         System.out.println(3);
         break;
   }
}
...

After decompiled, you will notice how is that Strings are now supported in switch statemens:

//in a class
...
public static void stringInSwitch(String str)
{
        String s = str;
        byte byte0 = -1;
        switch(s.hashCode())
        {
        case 110182: 
            if(s.equals("one"))
                byte0 = 0;
            break;

        case 115276: 
            if(s.equals("two"))
                byte0 = 1;
            break;

        case 110339486: 
            if(s.equals("three"))
                byte0 = 2;
            break;
        }
        switch(byte0)
        {
        case 0: // '\0'
            System.out.println(1);
            break;

        case 1: // '\001'
            System.out.println(2);
            break;

        case 2: // '\002'
            System.out.println(3);
            break;
        }
}
...

Yes... it's a lilttle trick. It's not like Strings are supported in switch statements directly, but their hashCodes are (hashCodes are integers). Looking at the code, I realize that it's better not to abuse using Strings in switch statements, because at the end, you get two switch statements...


Try with resources and Multi Catch
Remember the try with resources and multicatch example from the last post:

//in a class
import java.nio.file.*;
import java.io.*;
...
public static void copyFile(String src) 
              throws IOException, NullPointerException 
{
        Path path = FileSystems.getDefault().getPath(src);
        
        try (FileOutputStream fout = 
                        new FileOutputStream("file.dat")) {
            Files.copy(path, fout);
        } catch (NullPointerException | IOException ex) {
            ex.printStackTrace();
            throw ex;
        }
}
...

This example uses try with resources and multicatch all in one example. When I tried to decompile the generated class using JAD Java Decompiler, I got a lot of erros about the nested try statements, therefore I decided to try JD Java Decompiler and here is the result:

//in a class
import java.nio.file.*;
import java.io.*;
...
public static void copyFile(String src) throws IOException, NullPointerException
{
    Path path = 
         FileSystems.getDefault().getPath(src, new String[0]);
    try 
    {
      FileOutputStream fout = new FileOutputStream("file.dat"); 
      Throwable localThrowable2 = null;
      try 
      { 
        Files.copy(path, fout);
      }
      catch (Throwable localThrowable1)
      {
        localThrowable2 = localThrowable1; 
        throw localThrowable1;
      } 
      finally 
      {
        if (fout != null) 
        { //I added this { symbol for readability

          if (localThrowable2 != null) 
          { //I added this { symbol for readability

            try 
            { 
              fout.close(); 
            } 
            catch (Throwable x2) 
            { 
              localThrowable2.addSuppressed(x2); 
            } 

          } //I added this } symbol for readability
          else 
          { //I added this { symbol for readability

              fout.close();  

          } //I added this } symbol for readability

        } //I added this } symbol for readability
      }
    } 
    catch (IOException ex) 
    {
      ex.printStackTrace();
      throw ex;
    }
}
...

From the last piece of code, we can see how the compiler makes sure that any exception thrown during the copy process is not lost using the new (JDK 7) method +addSuppressed(Throwable):void of the class Throwable. This is important, because you will need all the possible exceptions when looking for a bug in your application. Also, notice that all the close operations are done in a finally statement ensuring that the resources are always closed at the end of the process.


Binary literals and underscores in literals
I think you can figure out what we'll get after decompiling this last feature...

//in a class
...
public static void coin() 
{
   int binaryNum = 0b10; //This is number 2 in binary code

   double value = 1000000000; //hard to read?
   double value = 1_000_000_000; //Easy to read with Java 7

   double value = 0b101010110111; //hard to read?
   double value = 0b1010_1011_0111; //Easy to read with Java 7

   double pi = 3.14_15_92; //another example of readability
}
...

Yep, nothing new... the compiler just rewrites the values without the underscores and translates the binary values to integer values:

//in a class
...
public static void coin()
{
        int binaryNum = 2;
        double value1 = 1000000000D;
        double value2 = 1000000000D;
        double value3 = 2743D;
        double value4 = 2743D;
        double pi = 3.1415920000000002D;
}
... 



Ok, that's all for this post. Hope you all like the new features of Project Coin (JSR334) in Java 7. There are more improvements to come in Project Coin II in Java 8 and we'll check them all in future posts.

see ya!


References:

Generics. Oracle [online].
Available on Internet: http://docs.oracle.com/javase/1.5.0/docs/guide/language/generics.html
[accessed on January 28 2012].

Overview of JDK 7 Support in NetBeans IDE. NetBeans [online].
Available on Internet: http://netbeans.org/kb/docs/java/javase-jdk7.html
[accessed on January 22 2012].

JAD Java Decompiler. Tomas Varaneckas [online].
Available on Internet: http://www.varaneckas.com/jad
[accessed on January 22 2012].

JD Java Decompiler. [online].
Available on Internet: http://java.decompiler.free.fr/
[accessed on January 31 2012].

Tuesday, January 24, 2012

Java 7 - Project Coin Decompiled

Hi all, it's time to start writing in 2012. As you may have seen already in other blogs, there are a few changes that can make your developer life a lot easier when programming in Java: diamond operator, Strings in Switch, try with resources, multi catch, etc. In this post (PART I) we are going to see some of the small changes presented in Java 7 Project Coin (JSR 334) and then (in PART II) we are going to decompile them in order to see what's the compiler doing (for educational purposes only).


What you need
NetBeans 7+ or any other IDE that supports Java 7
Diamond Operator
Generics helped us to reduce ClassCastExceptions among other things, but some times it can make the code hard to read. Diamond operator is a really nice change. Imaging that you need to group customers by city. You would need something like this:

//suppose the classes City and Customer exist
...
Map<City,List<Customer>> map = new HashMap<City,List<Customer>>();
...

Now, what if you also need to group the data by country:

//suppose the classes Country, City and Customer exist
...
Map<Country,Map<City,List<Customer>>> map = new HashMap<Country,Map<City,List<Customer>>>();
...

Now, it starts to be very hard to read, right? What if you also need to group by Region?

//suppose the classes Region, Country, City and Customer exist
...
Map<Region,Map<Country,Map<City,List<Customer>>>> map = new HashMap<Region, Map<Country,Map<City,List<Customer>>>>();
...

So what do you think? It's not easy at all to read code like that. Fortunately, the new Diamond Operator helps a lot in the readability of code. The last code can be recoded in Java 7 like this:

//suppose the classes Region, Country, City and Customer exist
...
Map<Region,Map<Country,Map<City,List<Customer>>>> map = new HashMap<>();
...

A lot better!


Strings in Switch
I've been waiting for this a lot!!! I remember the days when I was starting in the Java world and I really needed to use Strings in switch. Well, my  waiting is finally over. In earlier versions of Java you had to write something like this:

//in a class
...
public void stringToNumber(String str)
{
   if(str.equalsIgnoreCase("one"))
   {
      System.out.println(1);
   }
   else if(str.equalsIgnoreCase("two"))
   {
      System.out.println(2);
   }
   else if(str.equalsIgnoreCase("three"))
   {
      System.out.println(3);
   }
}
...

In Java 7 you can write it like this:

//in a class
...
public void stringToNumber(String str)
{
   switch(str)
   {
      case "one":
         System.out.println(1);
         break;
      case "two":   
         System.out.println(2);
         break;   
      case "three":
         System.out.println(3);
         break;
   }
}
...

Even NetBeans has an option to convert it automatically:





Try with resources and Multi Catch
This is a nice enhancement in this version, now you don't have to worry about closing those ResultSets, Statements, FileInputStreams...etc. You just need to use the new try structure and the compiler will care about it for you. You can even create your own classes to be Closeable (this is a new interface) by the new try structure. Following is a classic file access via streams:

//in a class
import java.io.*;
...
public static void copyFile(String path) 
              throws IOException, NullPointerException 
{
        File file = new File(path);

        FileOutputStream fout = null;
        FileInputStream fin = null;
        try {
            try {
                fout = new FileOutputStream("file.dat");
                fin = new FileInputStream(file);

                byte[] bytes = new byte[1024];
                int leido = 0;
                while ((leido = fin.read(bytes)) != -1) {
                    fout.write(bytes, 0, leido);
                }
            } finally {
                if (fout != null) {
                    fout.close();
                }
                if (fin != null) {
                    fin.close();
                }
            }
        } catch (NullPointerException ex) {
            ex.printStackTrace();
            throw ex;
        }catch (IOException ex) {
            ex.printStackTrace();
            throw ex;
        }
    }
...

If you notice, in order to be sure that the opened Streams are being closed once they finish, you have to code a try/finally block and close them by yourself. In Java 7, you can achieve the same behaviour in a better way and with less lines of code using the new try structure and the new NIO.2 classes:

//in a class
import java.nio.file.*;
import java.io.*;
...
public static void copyFile(String src) 
              throws IOException, NullPointerException 
{
        Path path = FileSystems.getDefault().getPath(src);
        
        try (FileOutputStream fout = new FileOutputStream("file.dat")) {
            Files.copy(path, fout);
        } catch (NullPointerException | IOException ex) {
            ex.printStackTrace();
            throw ex;
        }
}
...


Binary literals and underscores in literals
Now you can express an integer as a binary literal, this is ideal when programming low-level APIs, also you can use underscores in order to make your values more readable:

//in a class
...
public static void coin() 
{
   int binaryNum = 0b10; //This is number 2 in binary code

   double value1 = 1000000000; //hard to read?
   double value2 = 1_000_000_000; //Easy to read with Java 7

   double value3 = 0b101010110111; //hard to read?
   double value4 = 0b1010_1011_0111; //Easy to read with Java 7

   double pi = 3.14_15_92; //another example of readability
}
...

So, less code, more productivity and a better code readability that's what Project Coin is about! (Among other things not seen here).

That's it for PART I of this post, in PART II we are going to see what's the compiler doing when we Decompile the code we have seen here.


References:

Overview of JDK 7 Support in NetBeans IDE. NetBeans [online].
Available on Internet: http://netbeans.org/kb/docs/java/javase-jdk7.html
[accessed on January 22 2012].