Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.

Why Garbage Collection?

  • When objects are no longer needed, they should be destroyed.

  • This frees up the memory that they consumed.

  • Java handles all of the memory operations for you.

  • Simply set the reference to null, and Java will reclaim the memory

How Does Garbage Collection in Java work?

Java garbage collection is an automatic process. Automatic garbage collection is looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object. Any part of your program no longer references an unused or unreferenced object. So the memory used by an unreferenced object can be reclaimed. The programmer does not need to mark objects to be deleted explicitly. The garbage collection implementation lives in the JVM. 

To destroy an object in Java, you need to make it eligible for garbage collection. This means that you need to remove all references to the object, so that there are no more active references to it in your program.

Once there are no more active references to the object, the garbage collector will eventually remove the object from memory.

// create an object
MyObject myObj = new MyObject();

// set myObj reference to null
myObj = null;

// Call garbage collector
System.gc();

In this example, we create an object called myObj of type MyObject. Then, we set the reference myObj to null, which means that there are no more active references to the object. Finally, we call the garbage collector using the System.gc() method. This will remove the object from memory at some point in the future.

Note that calling System.gc() does not guarantee that the garbage collector will run immediately or that the object will be destroyed immediately. The garbage collector is a non-deterministic process and it will run on its own schedule.

  • No labels