bbbneo333
bbbneo333

Reputation: 122

Deconstructor in Java?

My java application can't work without static variables and I've declared a good amount of static variables in my application. But, there's a problem: Is there any deconstructor in java that i can use to free up the memory used by by these static variables? There's a Statement variable, for which i can use close() to free up some memory. I want to know, what really happens when stmt.close() method is called? PS: Is this possible, by providing a null value to the object (myStaticObject=null) and calling System.gc() will do the job?

Upvotes: 2

Views: 3257

Answers (4)

Alto.Clef
Alto.Clef

Reputation: 141

There is a finalize() method you can override. It will be executed if the object is collected by the JVM. However, there no guaranteed way to control the collection of the project. Call System.gc() works most of the time, depending on what the JVM thinks.

In a nutshell, what you said will work most of the time.

Hope this helps you.

Upvotes: 0

chiastic-security
chiastic-security

Reputation: 20520

If you want to free the memory of a static field x, then yes, just set

x = null;

Except in very rare cases, you shouldn't need to worry about calling the garbage collector yourself: the system will do that for you, and usually knows better than you when it's appropriate to do so.

All that said, a program with lots of static fields is usually a warning sign that the design isn't quite right. Good design usually (not always) associates fields with instances. You should at least ask yourself whether you should restructure your code.

Upvotes: 3

M A
M A

Reputation: 72874

The Java language does not have a deconstructor feature, since it has its own garbage collection, which relieves the programmer from manually freeing memory for no longer referenced variables.

stmt.close will close all database resources used by the Statement object. It does not tell the garbage collector that the reference is no longer used.

Yes you can invoke a one-time System.gc() after closing all resources (although this does not guarantee an immediate action by the GC thread), and after assigning null to the reference. However, assigning the null alone would normally be enough to tell the GC thread that the variable is no longer referenced without the need to explicitly run the GC.

Upvotes: 1

Matthias Steinbauer
Matthias Steinbauer

Reputation: 1776

Dear AnkitNeo you have given the answer yourself.

By setting the variable to null and calling

System.gc();

you will free up the memory. However, it is not guaranteed that System.gc() will actually garbage collect. According to this post: When does System.gc() do anything most of the time the system will garbage collect. I believe it will just not GC if there is currently a very high CPU load.

Upvotes: 3

Related Questions