Friday, September 2, 2011

Automatic Resource Management with Project Lombok

Last time I wrote about:
Read File Into String with Java 7
Its a sample of simple usage of new Java 7 NIO2 along with try-with-resource for automatic resource management.

I will take that example again but this time I will replace the try-with-resource statement with Project Lombok annotation processor @Cleanup. The @Cleanup annotation ensures that a resource close() method will be safely invoke (with no hassle) before the execution path exits current scope. OK, let's try it. I use NetBeans IDE 7.0.1 to create my example here. The ff. is my example:


With @Cleanup

To do automatic resource management with Lombok, I just annotate my local variable reader with @Cleanup and as a result, at the end of my read method scope, the reader.close() will be called.

The ff. is to show what exactly Lombok is doing under the hood:


After running Delombok.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.