Monday 13 June 2011

New Features in Java 5

Java 5 comes up with loads of new implementation which adds up to java 1.4 release. And also Java 5.o is known as Tiger release officially.

To start with, key features like Generics, Auto boxing/Unboxing, Var Args, Static Import, Enhanced For Loop, Type Safe Enums and Annotations.

There are couple of changes at the Virtual Machine, User Interface (Swing, AWT) and Base Library side as well.
As this post is targeted at the developers we would discuss on the Language features added to the ocean.

Generics
This long-awaited enhancement to the type system allows a type or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting. Refer to JSR 14.

Well, first of all, nobody can dispute that Generics are a solid concept that tends to improve the robustness of your code. The reason why they are so usually controversial regardless of the language is because of their implementation.
In a nutshell, I have this to say about Java generics: my code feels more robust, but it's harder to read.
So what's the problem?
Redundancy.
First of all, I have always had a hard time with the redundancy introduced by the necessity of casting in general. For example, instead of writing:
Map accounts = new HashMap(); // no generics ... Account a = (Account) accounts.get("Cedric");
why can't I just write:
Map m = new HashMap(); // no generics ... Account a = m.get("Cedric");
and let the compiler introduce a silent cast, since obviously, it's an object of type Account that I am trying to retrieve from the Map?
Obviously, Generics don't solve this problem entirely but they make a decent job at alleviating it somewhat. But they also make it worse in some other ways:
Map<String, List<Account>> accounts = new HashMap<String, List<Account>>();

Not only is the code significantly harder to read, but it fails to obey the DRY principle ("Don't repeat yourself"). What if I need to change the value type of this map from List<Account> Collection<Account>? I need to replace all these statements everywhere in my code. While IDE refactoring will help, it's still an awful lot of code for a modification of this kind that hardly impacts the semantics of this code.
Admittedly, there is no nice way to avoid this syntax when you are creating a new object, but what I am driving at is that I think Generics would have been better off if typedefs had been introduced with them.
Or so I thought at first.
But after thinking about it more, I realized that typedefs were the wrong solution to the problem, because simply put, they don't add anything to the use of a separate class to define your complex Generic type.
class AccountMap extends HashMap<String, List&lAccount>> { ... }
Except for the fact that you need to extend an implementation (HashMap, and not Map, obviously), this solution is probably better than introducing typedef, which has its own quirks.
I haven't gone to this trouble so far, but my recommendation would be: do it if you write the type more than three times (twice in the initialization and you use it more than once in your code).
Except for this little annoyance, I am quite happy with Generics overall and I particulary enjoy reading the TestNG Javadocs so nicely typed.

Enhanced For Loop
This new language construct eliminates the drudgery and error proneness involved in iterators and index variables when iterating over collections and arrays. ( impl of JSR 201)
Auto Boxing/UnBoxing
Easeness in conversions from primitives types to wrapper types. Say Integer to int, Boolean to boolean.

Check the below example for illustration
int i = 0;
i = new Integer(5); // auto-unboxing
Integer i2 = 5;  // autoboxing

Typesafe Enums
This flexible object-oriented enumerated type facility allows you to create enumerated types with arbitrary methods and fields.    It provides all the benefits of the Typesafe Enum pattern  without the verbosity and the error-proneness.

Variable Arguments simply VarArgs
Eliminates the manual ache to box up the array list arguments while invoking methods which accept variable arguments

Static Import
Avoids qualifying static members with class names without the shortcomings of the Constant Interface anti Pattern.

Annotations
Annotations basically does automation internally which does generate boiler plate code on the instruction of the developer. This leads to a declarative programming style where programmer specifies what to be done and the tool does the rest. Also eliminates the back up files to be kept up to date, instead the information is maintained the source file as meta data. (Refer to JSR 175)

Apart from these Language Feature Implementations, Java 5 also has crucial modifications done in the Tools section like  java compiler, javadoc tools.
Implementations at the Integration side also took place.
RMI, JDBC, CORBA, JNDI are the top level libraries modified to incorporate certain functionality.


New Features in Java 6

I was planning to post this for a long time, but found the time now. I looked at the JDK 6 and some new features are very good. Though I have to really get hands-on with this version, i managed to look under the hood and come up with a concise and "usable-for-everybody" list of new things.
First thing first – This version is a great great improvement on performnace. I did not do any profiling, but our programs are starting much faster. We deploy an EAR on JBoss. JDK 5 used to take atleast 75-80 seconds on my machine to come up, but with JDK 6, its consistently below 65 seconds on the same machine. JIT has also been improved, so I think part of it is coming from there.
Other features:
1. Scripting for Java (JSR 223): Now scripting languages can be used with Java. You get best of both worlds – flexiblity of scripting languages and power of Java. JDK 6 bundles a scripting engine for JavaScript (based on Mozilla Rhino). It also supports third party scripting engines and if you go to java.net, you can downaload and use engines for all popular scripting languages like PHP, Python, Ruby-on-Rails, AppleScript etc. The engines for XPath and XSLT are also available, though I have to see how to use them.
Scripting is good in many ways, like dynamic nature (no need of giving a datatype to a variable). Generally, a scripting language is good in doing few operations in a very efficient way, like PERL for text processing. These features can be exploited for faster implementation. Other advantage could be to integrate the legacy scripting code with new Java applications.
The new tool ‘jrunscript’ has been added to try out the things in scripting way.
2. Desktop features: There are many new features, but two are worth mentioning. One is ability to show the splash screen and other is the system tray icon. These two features are very useful and the overall experience of Java application will be more like a native application. The other thing is, everybody was doing it anyway in their own way. Now its not required as Java is here to help you out.
3. I/O: Two new good features. A new class ‘Console’ is added. It provides support for reading the passwords from console without displaying them.
Other is, in the File class new utility methods have been added for getting the total space on the disk, total free space on the disk and total usable space on the disk.
4. Networking: In JDK 6, cross platform NTLM is supported. It also comes with a default Cookie Manager. However, the biggest is that now JDK 6 gives you all required classes for creating a light-weight HTTP server. In fact, it also comes with a default implementation.
5. Monitoring and Management: Its very easy to find the deadlocked threads now using ‘findDeadlockedThreads’ method in ‘ThreadMXBean’. This could be very useful in error handling specially for enterprise applications. The error handler can restart the application when it detects the deadlock.
New classes and methods have been added to get a list of locks owned by a thread and also to find which stack holds the lock for a monitor. Another method that can help in desiging better application experience is ‘getSystemLoadAveage’. Apart from cosmetic value, this can be used to take certain runtime housekeeping opeartions.
I have to see what will be the performance penalty on using these methods. From the name of it, they look pretty expensive.
JMX has been upgraded to JMX 1.4 in JDK 6. JConsole, the swing based JMX client is now officially supported. It doesn’t work with JBoss though as JBoss comes with its own JMX implementation.
It is facinating to see how Java has transformed itself into JMX-aware machine. Most of the thing are controllable/viewable through JConcole.
6. Tools Package: A new package (javax.tools.*) is given for using the Java tools in programmatically. The most useful one, I guess is JavaCompiler. It allows you to invoke the compiler programatically in a standard way.
7. Others:
a. Profiles and debuggers can now attach to running VM. The VM doesn’t need to be started in a debugging-capable mode. This will be a huge help in the diagnosis.
b. RMI calls can be made over SSL.
c. Few new Collection interfaces are added.
d. JAR tool will maintain the timestamps of the files while extracting them.
e. JAXB has become part of JDK 6. ‘xjc’ tool also comes with JDK now to generate the binding classes. However, there is no compatible ANT task (so far), so you will have to use ‘exec’ in the build scripts for using ‘xjc’
f. DerbyDB (formerly Cloudscape) is bundled with JDK. This can be used for DB operations in the development time.

Following are the new features in SE 6.
  1. Changes in I/OThis is a new feature added in Java SE 6, which has the ability to read text from a terminal without having it echo on the screen through java.io.Console.
      
  2. Collections Framework EnhancementIn Collection framework, we are able to improve the performance hashing function that is used by java.util.HashMap. It provides some new Collection interfaces also.
      
  3. Changes in jar and zipJar and zip support has been enhanced in JDK 6. In this, two new compressed streams have been added. These are java.util.zip.DeflaterInputStream and java.util.zip.InflaterOutputStream.
      
  4. Java Web Start enhancements in version 6The cache format of Java Web Start and Plug-In has been fully changed. All dialogs have been redesigned and consolidated between Java Web Start and Plug-In to be more user friendly.
      
  5. JMX API EnhancementsEnhancements has been made to the JMX API in Java SE 6 like : JMX API now completely supports Generics, MXBeans have been added and much more?
      
  6. Java Platform Debugger Architecture EnhancementsJVMDI has been deleted in JAVA SE 6 and JPDA has been added. Some new Methods are included like boolean boolean canGetInstanceInfo() and much more?
      
  7. Java SE 6 Monitoring and Management EnhancementsAPI provided by JAVA SE allows you to monitor and manage the JVM in the package java.lang.management. JAVA SE 6 includes some enhancement to this API.
      
  8. New Package java.util.spi in JDK 6A new package Java.util.spi has been included in JAVA SE 6.
      
  9. Networking features and enhancements in Java SE version 6.0This feature include enhancement in networkInterface, support for Internationalized Domain Names, HTTP Negotiate Authentication and much more?
      
  10. Enhancements in java.lang.Class and java.lang.reflectSome new Methods are included in java.lang.Class like : getInterfaces(), getClasses(), getConsturctors(), getMethod(String, Class?) and much more?.
      
  11. Enhancement in RMI for JDKTM 6java.rmi.MarshalledObject now support generics
      
  12. JAVA SE 6 Security EnhancementsJAVA SE 6 has added support for some security functionality: the XML Digital signature API and implementation, Smart Card I/O API. And much more?
      
  13. Serialization Changes and Enhancements in JAVA SE Development Kit 6The new method ObjectStreamClass.lookupAny now used to obtain an ObjectStreamClass instance for a non-serializable Class
      
  14. JavaTM Virtual Machine TechnologyDTrace support has include in Java SE 6 HotSpot VM. The hotspot provider makes available probes that can be used to track the lifespan of the VM, thread start and stop events
      
  15. Scripting for the Java PlatformBy using this Features developers integrate Java technology and scripting languages by defining a standard framework and application programming interface (API)
  16. Leveraging Security in the Native Platform Using Java SE 6 TechnologyThe JAVA SE 6 provide a large set of security APIs. These Security APIs span a wide range of areas, including cryptography public key infrastructure, secure communication, authentication, and access control.
  17. JAX-Web Services 2.0 With the Java SE 6 PlatformMost exciting new features of the JAVA SE 6 is support for the Java API for XML Web Services (JAX-WS), version 2.0.

No comments: