|
Memory is an essential resource for running any computer program. Moreover, it is a limited resource. In normal execution of program, memory is continuously allocated and released. The released memory must be recycled so that it can be reused for further allocation. Most languages have memory management techniques to deal with allocation and release of memory. Languages such as C, C++ have manual memory management in which, you (as programmer) need to allocate memory whenever you need it and you are responsible to release it. This approach has some serious drawbacks.
1. You may release the memory too soon causing corrupted data if that memory is sill being referred by the program.
2. You may forget to release the memory altogether causing memory shortage.
Java tackles these problems with automatic memory management. It allocates and frees the memory. Since Java manages the memory, you (as programmer) need not worry about allocating the memory at the time of creating object or freeing it after you are finished working with the object. In part–I, we saw that when you create an object with a new keyword, Java allocates heap-memory to the newly created object. This memory remains allocated throughout the lifecycle of the object. When the object is no more referenced, this allocated heap-memory is eligible to be released back to the heap as a free memory. The mechanism Java uses to automatically release the allocated memory is called as the automatic garbage collection.