Krypton
Krypton

Reputation: 3325

Java memory collection usage

I have a try catch and finally block like this.

Client client = new Client();
try {
   ...
}
catch {
   ...
}
finally {
   client = null;
}

I would like to ask if client = null is necessary to wipe out memory use for client object if exception occurs.

Upvotes: 2

Views: 267

Answers (4)

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

As soon as the client variable is no longer reachable (ie no longer has a GC root) it is eligible for garbage collection.

In your example it appears as if client will be unreachable as soon as the method exits (whether by an exception being thrown or a 'normal' return), so assigning it to null is unnecessary.

Upvotes: 4

Caffeinated
Caffeinated

Reputation: 12484

No, Java's garbage collector takes care of this.

I would tattoo this on my forehead, as this is one of Java's big strengths in relation to C/C++.

Upvotes: 1

kundan bora
kundan bora

Reputation: 3889

Client object is subject to scope.If Client object has class scope then it will live until class will load, if client has method scope then it will live until control will be inside method.

there are many scopes besides these two.

so need not to wipe out object. You only need to wipe out when some resource are used like File IO or Database connection.

Upvotes: 2

Flaise
Flaise

Reputation: 591

Whenever an object has no references to it for any reason then it becomes eligible for garbage collection, including if a variable goes out of scope as a result of the program leaving a function or statement block. In other words, no.

Upvotes: 3

Related Questions