DEV Community

haytam_7
haytam_7

Posted on

Garbage Collector: The Desirable Aspect of Java

So what is a garbage collector? đźš®
Each time we declare an object we use a system resource known as memory.
And here are some questions that spring to mind:

  • What happens to the objects that we no longer need?

  • Do we have to care about freeing up the space we are using?

Fortunately, Java programmers need not to care about objects that are no longer in use, that's because Java automatically frees up this space and destroys these unreachable objects and this reduces the chances of having memory leaks (which are common in other languages)

Top comments (4)

Collapse
 
mainrs profile image
mainrs

I wouldn’t call it “reducing the changes of having memory leaks”. Java just gets rid of the manual memory management for you. Garbage collection does not magically remove memory leaks. It just removes one incident.

However, it does also introduce new problems. What if two objects reference each other? But you don’t reference one of them. A “basic” implementation wouldn’t collect them since they each have a valid reference and seem to get used. Cyclic dependencies are a GC’s nightmare.

Collapse
 
haytamkh7 profile image
haytam_7 • Edited

The garbage collection reclaims the used resources that are no longer in use. It's like saying "When there are no references to an object, the object then is ready to be collected".
Memory that is not automatically reclaimed usually leads to a memory leaks, a situation that is less likely to happen in Java.

Collapse
 
dagnelies profile image
Arnaud Dagnelies

It's not really Java specific. Python, JavaScript, C#... Almost all modern programming languages have garbage collection. Manually allocating/freeing memory is reserved for more low level languages like C/C++.

Collapse
 
haytamkh7 profile image
haytam_7 • Edited

Hi Arnaud,
I didn't mention that this feature is ONLY available in Java, instead I tried to show a 'special' feature in Java.