Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Painless resource management in java

Tags:

java

resources

In C++ we acquiring a resource in a constructor and release it in a destructor.

So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever.

AFAIK java classes don't have destructors. So how does one do the resource management in Java.

For example:

public int foo() {    
    Resource f = new Resource();
    DoSomething(f);
    f.Release();
}

How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we?

like image 511
Serge Avatar asked Sep 12 '08 09:09

Serge


People also ask

What is Java 7 arm feature?

ARM in Java stands for automatic resource management, it was introduced in Java7, in it the resources should be declared at the try block and they will be closed automatically at the end of the block.

How try-with-resources works internally in Java?

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.

How try with resource work internally?

In the try-with-resources method, there is no use of the finally block. The file resource is opened in try block inside small brackets. Only the objects of those classes can be opened within the block which implements the AutoCloseable interface, and those objects should also be local.

How do you release a resource in Java?

Java automates the reclamation of memory, but not other resources. A finalize() method can help ensure that resources are released eventually but not in a timely fashion. It appears that this has been handled ad-hoc in various Java classes -- some have close(), some dispose(), some destroy(), and probably others.


2 Answers

Yes you can and should put try/catch/finally block around your code. In C# there is a shorthand "using" statement, but in Java you are stuck with:

public int foo() {
    Resource f = new Resource();
    try {
        DoSomething(f);
    }
    finally {
        f.Release();
    }
}
like image 57
qbeuek Avatar answered Sep 24 '22 04:09

qbeuek


This question dates to 2008 and therefore pertains to Java 6. Since then Java 7 has been released, which contains a new feature for Automatic Resource Management. For a more recent question that is relevant to Java 7 see this question:

java techniques for automatic resource release? "prompt cleanup"?

like image 43
Raedwald Avatar answered Sep 20 '22 04:09

Raedwald