These are my own views. If it does not match with any texts or if they are different I am not a person to be blamed. Use it on your own risk. ;-)
Last week one of my friends asked me 4 very good questions on GC. So I replied him and part of that i am putting here.
Java has a powerful mechanism known as garbage collection. When object goes out of reference/scope it becomes eligible for garbage collection.
The time garbage collector runs the objects eligible garbage collections are removed from the heap i.e. when object is destroyed its memory is freed and its added as free space in the garbage collector heap's free space.
Implentation Garbage collector can be done using several algorithms one of them is ref. counting.
Java does not provide destructors to stop memory leaks. But it provides finalize method. You can say its a kind of a destructor. When ever any object is destroyed from the heap JVM searches for finalize method if object has finalize method it runs it. Generally its used to free database connections and other shared resources.Actually its safe to forget about the object instead of writting finalize method because finalize method written wrongly will stop GC to collect the object and it will be dangling on the heap. (in case you are having the ref to some other object some other object is not eligible for the GCollection.)
Overhead in terms of if GC finds finalize it runs it and adds overhead;) so its a good practice not to write finalize method your self until you are very sure of the runtime behaviour of the objects.
And finalize method runs at the most one time in the life of the object's life cycle.
You cannot force garbage collector to run. But you can request it using System.gc() and another method is Runtime.gc() But its not sure if GC will listen to your request. ;-)
Friday, 18 April 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment