Utilizing the Power of Garbage Collector

As part of our ongoing mission to connect brilliance with opportunity, we regularly hold webinars and events for our Andela Community. We open up the floor to our technologists to discuss what they’re most passionate about, from building Docker environments to ReactJS dos and don’ts.

Recently, our very own Amuda Adeolou Badmus hosted a webinar focusing on the ‘behind the scenes’ of garbage collection.

In this blog, Amuda details the essentials of garbage collection – and offers tips on how best to utilize its many benefits!

What is Garbage Collection?

Any system that’s unable to eliminate unused or unreferenced resources will stop working or ‘die’ at an early stage. Garbage Collectors enable the system to reclaim memory that is no longer used or referenced.

Garbage collection (otherwise known as GC) is a memory recovery feature built into programming languages, including Python and JavaScript. A GC-enabled programming language includes one or more garbage collectors (GC engines) that automatically free up memory space that’s been allocated to objects that are no longer needed by the program. The reclaimed memory space can then be used for future object allocations within that program.

Garbage collection is an important part of software development since it keeps programs from using up too much RAM. Besides helping programs run more efficiently, it can also prevent serious bugs, such as memory leaks, that can cause a program to crash.

How GC works 

Every programming language, from C# to HTML, implements GC differently, but they share a common similarity in the process that occurs automatically behind the scenes. Some garbage collection enabled languages provide controls for launching the GC process, but the implementation of controls varies from one language to the next. You can add garbage collection capabilities into a language via a library or module.

Garbage collection is an important, necessary component in most modern programming languages. But despite its many benefits, GC can harm performance, as it is an ongoing process that requires central processing unit resources, which can adversely affect an application’s operations. As a result, some technologists are still on the fence about GC’s benefits, believing they can better control memory deallocation than an automated process.

But, GC’s popularity and longevity – its built into most modern programming languages – means that its it’s the central approach to memory management for developers and engineers. As technology evolves and programming languages update, they continue to improve their GC capabilities, using different techniques to reduce any negative impact on performance.


Processes involved in Garbage collection

[1.] Marking: Marks all objects that are currently used, referenced, or alive.

[2.] Sweeping: Unmark, remove the unused objects and reclaim the free space.

[3.] Compaction: Traversing, and moving all referenced objects to survivor space for memory reclamation.

For scenarios where GC was unable to garbage collect unused resources, then the system throws an OOM (OutOfMemory exception) which will then result in the system stopping altogether.

Tips to enhance timely Garbage Collection, and how avoid memory leakages

[1.] Avoid try with finally keyword

Reason 1 : 

When the output.close() statement in the finally block throws an exception, then the input stream will be leaked which could be resolved by nesting try-finally construct.

 Reason 2 : 

Even if an unhandled exception occurs occasionally, leaked resources can build up over time.

Reason 3 :

 Aside from the unpredictable latency, and unconstrained behavior. It also has security vulnerabilities and unreliable execution.

What you should do

[2.]Prefer using the “try-with-resources”

Ensures resources are used so that their close methods are guaranteed to be called, regardless of whether exceptions occur or NOT.

[3.] Avoid using System.gc()

 Reason 1 : 

Since heap (The area of memory used to store objects instantiated by applications running on the JVM) itself grows independently of Java allocations, calling System.gc() is not an effective and efficient way to return unused memory.

Reason 2 :

In a multithreading system, it’s difficult to determine the unused resource to remove.

[4.] Nulling object reference

When you’re sure a reference object is no longer needed, un-reference it by assigning it to a null.

When an object becomes unreachable, it becomes eligible for Garbage Collection (GC)

Example:


[5.] Avoid creating unnecessary new objects during iteration

Example:

[6.] Prefer primitive over boxed primitive

Example

Reason 1 : 

Primitives only have values; boxed primitives have identities distinct from their values. 

Reason 2 : 

Primitive types have only one fully functional value, whereas each boxed primitive type has one nonfunctional value (null).


Reason 3:

 Primitives are more efficient(time and space) than boxed primitives.

[7.] Avoid having too many static variables

Reason 1 : 

Static fields have a life that usually matches the entire lifetime of the running application.

Reason 2 : 

 Once the object remains alive, the required heap memory will be directly proportional to the invoked Object, and while unused/unreferenced object(s) point to a null reference.

[8.] Consider using composition

[9.] Override equals and hashCode methods

 Reason 1 : 

When using ORM frameworks, there is a high potential of memory leakages if these methods aren’t overridden because it wouldn’t be able to compare objects and would fill its cache with duplicate objects.

I hope you find this useful.

Want to be part of the Andela Community? Then join the Andela Talent Network!

With more than 175,000 technologists in our community, in over 90 countries, we’re committed to creating diverse remote engineering teams with the world’s top talent. And our network members enjoy being part of a talented community, through activities, benefits, collaboration, and virtual and in-person meetups.

All you need to do to join the Andela Talent Network is to follow our simple sign-up process. 

Submit your details via our online application then…

Complete an English fluency test – 15 minutes.

Complete a technical assessment on your chosen skill (Python, Golang, etc.) – 1 hour.

Meet with one of our Senior Developers for a technical interview – 1 hour.


Visit the Andela Talent Network sign-up page to find out more.

If you found this blog useful, check out our other blog posts for more essential insights!

Related Posts