Definition of Garbage Collection in Java

Definition of Garbage Collection in Java thumbnail
Without the garbage collector, the heap may fill up with unused objects, preventing new objects from being created.

In Java, when an object is created using the "new" operator, the object is given a place in the program's memory space known as the "heap." The size of the heap is limited however, so a method of reusing heap space is required.

Garbage collection is a process of cleaning up unused objects, reclaiming their allocated memory. When an object is no longer referenced anywhere in the program, the garbage collector will automatically erase the object, freeing up space on the heap to be used by other objects.

  1. Memory

    • The computer's memory is where data that is in use by the program is stored. Portions of system memory are assigned to different processes by the computer's operating system. The assignment of portions of memory to processes or objects is known as "allocation."

      The correct allocation and distribution of memory is very important to the functionality of the computer.

    The Heap

    • When a Java program is first executed, it will request some memory space from the operating system. Some of this memory will be used for the program's heap, the area where the program will store objects created using the "new" operator.

      The computer's memory, and therefore the program's heap, is limited in space. If the program continued to add new objects to it without deleting old ones and freeing memory space, the heap would quickly fill up and cause an error. The process of controlling the allocation and reallocation of memory is called memory management.

    Manual Memory Management

    • Different programming languages handle heap memory management in different ways. Some programming languages like C and C++ use manual memory management, forcing the programmers to free unused memory themselves.

      Manual memory management can lead to bugs such as memory leaks if the program is coded incorrectly, and can make programs more complicated to write.

    Garbage Collection

    • Programming languages with garbage collectors--such as Java--clean up unused memory automatically, preventing bugs and reducing complications for the programmer.

      Java's garbage collector works by monitoring which objects are still actively referenced. If an object is still referenced by the program, it is "alive" and the garbage collector ignores it. If an object is no longer referenced anywhere in the program however, it is "dead" and garbage collector will free its memory space.

Related Searches:

References

  • Photo Credit Jupiterimages/Photos.com/Getty Images

Comments

Related Ads

Featured