Thursday, August 25, 2011

Java 7 and ARM - no need for close!

If you haven't seen them yet, there are some pretty nifty new language enhancements coming (er… here) in Java 7!

One such feature allows you to remove your close!!!

No, not clothes, .close()! Lets take a look...

Spozing' you have a nifty little method that’s in charge of writing every object in a list to an ObjectOutputStream. If one were in a hurry one might write something that went a little like this:

try{
     ObjectOutputStream objectOutput = getDefaultObjectOutputStream();
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}

Now, ignoring the fact that I'm catching any old error here, do you see anything else wrong with this picture?... Take a good look… Do ya see it?...

Aha! I've got no close() !

Having caught the issue one might decide to modify the code a little bit and do something like the following:
ObjectOutputStream objectOutput = null;
try{
     objectOutput = getDefaultObjectOutputStream();
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}finally{
     objectOutput.close();
}
But that’s ugly! I'll have to modify the method this is in to throw IOException (since I'm not handling it in the finally) and I might want to check that objectOutput isn't null before calling close (just in case something went awry in getDefaultObjectOutputStream(), which I didn't do!).

Thanks to some nifty new features in Java 7, I don't have to remember my close() anymore! Java remembers my close() for me!

Applying the new fanciness to the above, I can go ahead and do this:

try(ObjectOutputStream objectOutput = getDefaultObjectOutputStream();){
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}

Thanks Java 7!

If your curious about this, take a gander at ARM (automatic resource management)...

If you want to check some of the new stuff out yourself in the comforts of a reasonably friendly IDE, I'd check out the Netbeans beta! Eclipse hasn't added support for the new JDK 7 so unfortunately, I wasn't able to play around in my IDE of choice ;)

There'll be more posts from me on the way, but right now I want to play! Hooray Friday!

No comments:

Post a Comment