As Tsaman said, the secret is finally used; usually,
Resource r = allocateResource(); try { // use resource } finally { r.dispose(); }
What should be noted here:
- try and finally create a variable region. Therefore, highlighting your resource in the try clause will not work, because it will not be visible in the finally clause - you need to declare the resource variable before the try statement.
If you have several resources to allocate, the general template is applied cleanly, but this is often not obvious to beginners:
Resource1 r1 = allocateResource1(); try { // code using r1, but which does not need r2 Resource r2 = allocateResource2(); try { // code using r1 and r2 } finally { r2.dispose(); } } finally { r1.dispose(); }
etc. etc. if you have more resources to allocate. If you have a couple of them, you will probably be tempted to try to avoid the deep nesting of attempts ... finally. Not. You can get the right to free resources and handle exceptions without investing so many attempts ... finally asserting, but getting this right without trying to nest ... finally even more ugly than deep nesting.
If you often need to use a set of resources, you can implement a functor-based method to avoid repetition, for example:
interface WithResources { public void doStuff(Resource1 r1, Resource2 r2); } public static void doWithResources(WithResources withResources) { Resource r1 = allocateResource1(); try { Resource r2 = allocateResource2(); try { withResources.doStuff(r1, r2); } finally { r2.dispose(); } } finally { r1.dispose(); } }
What you can use as follows:
doWithResources(new WithResources() { public void doStuff(Resource1 r1, Resource2 r2) {
doWithResources automatically handles the allocation and release correctly, and your code will have fewer repetitions (which is good). But:
- Java syntax for anonymous classes is overly verbose
- Checked exceptions in doStuff complicate things too much.
two points that I hope will be resolved in Java 7.
This code can be found in Spring, for example:
alex
source share