Reputation: 5335
I have some question over here regarding the java garbage collector.
First let me clear what I have understood regarding the Java GC.
GC
is a background thread will always run in the background when the JVM starts.
Each object having one finalize() method. This method is used to release the
system resources before the object is destroyed. According to java experts,
we should not put the resources under finalize() method for releasing the
system resources. Becuase we cannot make sure when the GC will run. But we can
request the GC
to run by calling System.GC()
.
So now my question is, GC
is a background thread will always run in the background.
Now how can we say that we dont know when the GC
will run? Is the statement like this "we dont know when the GC will call finalize() method "
Is that the meaning of that? If that is what they meant, then what is the job
of GC
? GC
's responsibility to find out the un used variable and remove from the memory.
In that case,why GC
cannot call finalize() method also?
Upvotes: 0
Views: 191
Reputation: 2190
Now how can we say that we dont know when the GC will run?.
Functioning of GC is dealt by complex Algos, which is dependent on underlying OS and Hardware. WE can't say because if one tell about a particular JVM version it will not be valid with other JVMs. So it better we can't rely on that.
what is the job of GC.
GC finds reference less objects (read type of ref. for more) and reclaims memory used by them.
n that case,why GC cannot call finalize() method also?
So that's sure finalize method will be called but it's not sure when. Because evenif you know in your JVM when finalize() method will run, you never know when in other JVMs. So, if you deal with some really expensive resources in your finalize method, your programe may crash in other JVMs.
Upvotes: 2
Reputation: 20442
Simply put, GC will run at an indeterminate time, so system resources would not be freed in a timely manner if finalize
is relied on to free them. It doesn't make sense to wait for the GC to reap the heap space of an object holding a system resource when most program logic should be easily designed to simply release the resource when it is no longer in use.
On a somewhat related note. One of the issues that caused early versions of the JVM to be so slow was calling finalize
. Thus, modern JVMs will skip calling finalize
whenever possible. So relying on finalize
could also have a performance impact.
Upvotes: 0