Vinay Prajapati
Vinay Prajapati

Reputation: 7546

Should we assign local object references to null in a finally block?

Should we reference Objects to null in finally block while Objects are in local scope of method? What are the performance issues resolved by doing so?

code:

Map<String, Map<String, String>> getData(Map<String, String> params) {
    StringBuilder query = new StringBuilder(); // Construct query using it
    ResultSet rs = null;
    try {
        rs = DataUtil.getData(query);
        while(rs.next) {
            // store data in return Map
        }
    } catch(ConnectionException ce){
        ce.printStackTrace();
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        rs = null;
        query = null;
    }
}

Here, freeing up rs and query seems to fulfill no purpose as they are automatically valid for garbage collection after method execution. Any help would do great.

Upvotes: 0

Views: 1388

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200296

There are edge cases where this can matter quite a lot: it can make the difference between a running program and an OutOfMemoryException. Consider this code:

long[] hugeAry = new long[Integer.MAX_VALUE]; // barely fits on the heap
... work on hugeAry;
hugeAry = null;
int[] intHugeAry = new int[Integer.MAX_VALUE];
... work on this one

Commenting out hugeAry = null will easily cause an OOME. The cases can get even more bizarre than this—check out this related topic on SO.

But, don't get me wrong: in 99.9% of cases, nulling out locals (in finally or otherwise) does not matter.

Upvotes: 1

Keerthivasan
Keerthivasan

Reputation: 12890

There is no need to do so. There is no benefit at all. Local variables are not reachable once the execution gets out of the method. GC will be done on all objects which are not reachable. This is no where related to performance issues.

Upvotes: 1

LionC
LionC

Reputation: 3106

No we should not. It makes the code a lot harder to read and in most cases (for example your example) it does absolutely nothing, as GC will start after the scope anyways.

In general we should let Java handle its Garbage Collection and should not try to make it more efficient by writing strange code.

Upvotes: 1

iamyogish
iamyogish

Reputation: 2432

No don't do this because it doesn't mean anything when object is out of scope. All the java objects deallocation will be handled by Garbage Collector automatically when there is no owner or reference to that object in heap.

Finally is very handy because it'll get executed whether there occurs an exception or not in your code. Use finally when you want to perform some important resource management work like closing an opened database connection etc. HTH

Upvotes: 1

Related Questions