4

I'm converting some C# code to Java and it contains the using statement. How should I replicate this functionality in Java? I was going to use a try, catch, finally block but I thought I'd check with you guys first.

raven
  • 18,004
  • 16
  • 81
  • 112
James
  • 2,306
  • 1
  • 22
  • 23

3 Answers3

8

That's correct. A C# using block is just syntactic sugar for that anyway. The closest Java equivalent to IDisposable is Closeable.

There is a proposal (which is partially committed already), called Automatic Resource Management, for adding similar functionality to Java 7. It would use try-finally behind the scenes, and proposes creating a new Disposable interface (which would be a superinterface of Closeable).

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 3
    ARM is now in so it's not a proposal anymore: http://hg.openjdk.java.net/jdk7/tl/jdk/rev/c4d60bcce958 – Esko Jul 05 '10 at 16:30
  • 2
    Technically I think just the API support for ARM is in, but the rest is coming. – ColinD Jul 05 '10 at 16:37
2

The standard idiom for resource handling in Java is:

final Resource resource = acquire();
try {
    use(resource);
} finally {
    resource.dispose();
}

Common mistakes include trying to share the same try statement with exception catching and following on from that making a mess with nulls and such.

The Execute Around Idiom can extract constructs like this, although the Java syntax is verbose.

executeWith(new Handler() { public void use(Resource resource) {
    ...
}});
Community
  • 1
  • 1
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • Java 7 now has try-with-resources on Closable objects - an analog to using on IDisposable objects. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – csauve Dec 17 '14 at 15:49
0

Don't forget the null checking! That is to say

using(Reader r = new FileReader("c:\test")){
    //some code here
}

should be translated to something like

Reader r = null;
try{
    //some code here
}
finally{
    if(r != null){
         r.close()
    }
}

And also most close() in java throw exceptions, so check DbUtils.closeQuietly if you want your code to be more c# like

Michael Celey
  • 12,645
  • 6
  • 57
  • 62
Pablo Grisafi
  • 5,039
  • 1
  • 19
  • 29