BKStart a conversation ↗

smart_ptr in Java 1.7

Darn it but I’ve been doing a lot of Java recently and u know what, I’m no expert but I think I could even raise the rating on my C.V. at this stage. My first experience of Java was reading a book back in 2001 belonging to a student friend of mine, the book was lying about so I picked it up and read it over the course of a week (yes I had an early addiction to technologies even though I was living in C++ land at the time). I ended up helping with one final year project, a Java applet game suite if I remember correctly and in a JBuilder IDE.

Over the years I quickly forgot about my little affair with Java and got deeper into C++ which I have to say I loved, around the same time I was having another affair (yes I was a slut) with Microsoft .NET beta2. I can’t put my finger exactly on why C# won out for me, but I spent the next few years working on C++ and C#, Java was just something I always left to one side. I always thought hey Java will be easy, I’ve programmed in C#, same concepts, and moreover I knew C++, so well then C# or Java are a walk in the park; while this I guess is partially true, but you’re not prepared for the curve/slope/cliff you’ve got to climb to learn the IDE and the libraries needed these days.

I’m currently working for a data management company, our products are written in Java and .NET. For the first two years I managed to live in the .NET world but lately and mostly due to the success of some of our newer components I’ve been doing quite a lot of Java, (a lot more than I ever expected). I’ve also started reading some good books on the subject and you know what I’m as likely to start a test application in Eclipse as I am in VS2010 these days (at least as far as the product components are concerned).

So what’s changed? Well for one the Java language is evolving once again which is exciting; so to continue on my smart_ptr series of posts, we can now achieve resource cleanup with Java 1.7 with the AutoCloseable interface.

For .NET people this will be very familiar to IDisposable and the using(var x = new IDisposableDerivedType()).

File file = new File("input.txt");

InputStream is = null;

try {
is = new FileInputStream(file);

// do something with this input stream
// ...

}
catch (FileNotFoundException ex) {
System.err.println("Missing file " + file.getAbsolutePath());
}
finally {
if (is != null) {
is.close();
}
}

Java 7: Try with resources

File file = new File("input.txt");

try (InputStream is = new FileInputStream(file)) {
// do something with this input stream
// ...
}
catch (FileNotFoundException ex) {
System.err.println("Missing file " + file.getAbsolutePath());
}

We’re guaranteed that the is.close(); gets called automatically for us. Have to say I'm a bit jealous that the C# team didn't think of the try() syntax over using.