In C++ when we create an object using "new" operator, the memory is allocated for this object and we use it in our program. When we think that we do not need this object anymore, we return this memory to the heap and hence this memory is available for other applications (programs). This operation is done by using "delete" operator in C++. But if we don't delete this object and make it unreferenced, then we will never get this memory back until we restart our computer. Because it is allocated for our program and no other program can use it until we free it. And if this process of allocation and not returning back is in loop, then after sometime our memory will get finished and computer will stop responding. The unavailability of this unreferenced memory is called memory leak. It is programmer's responsibility to free unused memory for other applications.
Java frees the programmer from this responsibility. The JVM (Java Virtual Machine) takes this responsibility. It look after some time for unreferenced memory and if find any memory locations, it sent back them to heap. Now lot of problems are solved with this technique. This process is called garbage collection. The Garbage collector of java runs and checks, if there is any unreferenced memory is there left by any java program and makes it free for other programs.
Garbage collector runs when it feels that most of CPU resources are free. If there are many heavy applications are running there, then garbage collector will not run. Anyway programmer is free now. GC (garbage collector) runs automatically but you can request to run GC to JVM. Your request will not instantly invoke the GC, again it depends on CPU resources and some other factors.
To request for invoking the gc Systemgc() method is used.
No comments:
Post a Comment