Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Finalizers, what tasks are really necessary

ArrayList<Object> foo;
Object[] bar;

typical finalizers will do

foo = null;
bar = null;

My question, will ArrayList call a finalizer wich sets any pointers it holds to null, or do I have to step through the list an do

for(i=1; i<foo.size(); i++) foo.set(i,null); ???

And the other question: for an array, do I need to set any of its contents to null, like

for(i=1; i<bar.length; i++) bar[i] = null;

or is it enough that the whole memory block is discarded and any pointer in it out of scope afterwards?

Sorry, if the question is stupid.

After reading through the answers I figured out, that there is nothing to implement there on your own.

Some sources suggest that if something like this (memory eating apps) happens, that this is by bad design.

My core question is: Doing often

struct = new LargeStructure();

does this exaust memory?

Or does this only need the memory of one of this structures?

BTW: The problem occours in a webapp running tomcat, and there is only one session active wich holds the described pointer as a session variable.

like image 729
user715484 Avatar asked Jun 15 '13 16:06

user715484


1 Answers

All objects will be eligible for GC by Garbage collector automatically when they are no longer referenced. You don't have to worry about it. If you are setting the array reference to null , then the array object itself is eligible for GC if there are no other live reference to the array object, the elements of the array will be eligible for GC if there are no live references to them anymore.

As per the documentation:

protected void finalize() throws Throwable

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

The finalize() method will be called after the GC detects that the object is no longer reachable, and before it actually reclaims the memory used by the object. If the object never becomes unreachable, or the GC doesn't run then finalize() may never be called.

You can try to force the JVM to call finalize() by calling System.runFinalization():

Runs the finalization methods of any objects pending finalization.

Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.

like image 157
AllTooSir Avatar answered Oct 29 '22 17:10

AllTooSir