Garbage Collection
Disclaimer: There are enough articles and videos about Garbage collection.
This is just another one. Specially because “Diwali is coming”.
What is Garbage collection?
Let’s not start with the definition.
“ I keep throwing garbage out, and you keep bringing new ones in the house”
~ Probably every parent ever
Here, parents can be considered (garbage) collectors. ;)
Now, if you started thinking that when one sees some junk lying around, one doesn’t just collect it, but also throws it out. Well, you already understood what a garbage collector does.
Garbage collectors scan the area, find which things are unnecessary, and collect them, but only to throw them out in the end.
In computer science, the garbage collector is a live compiler entity (process/thread) that keeps a watch on memory and removes the items that aren’t in use anymore.
Why do we need garbage collection?
In the real world, a child may try her hand on painting, and end up making a mess only to generate an indistinguishable sunset painting. You may not be asked to clean that up. Mostly because of some past instances where the results of the activity were counter-intuitive.
Similarly, in the computer world, a process may bring too many items in memory to process them. It can be to calculate the sum of things, to mine a bitcoin, or just because a lousy programmer like me asked her to do so. Some languages like Java, Go lets the programmers free of the headache of managing memory by guaranteeing it will be taken care of automatically.
Compiler to programmer be like : “Main Hoon Na”
When to collect the garbage?
A very valid question! When you were a child, where did your parents usually clean your room?
- didn’t care about it until it was unbearable
- every day or once a week (periodically)
- when it seemed filthy
These are all sound strategies on when to collect the garbage for a program as well. Different algorithms have different approaches
- No GC (clean it when there is no space left)
- Periodic or in a continuous manner (most of the algorithms)
How to collect the garbage?
Before we move to how to collect garbage, one thing to understand here is what do you call trash and what’s not. It’s fair to assume the memory that is currently in use is not garbage.
Can we keep track of each memory byte/reference, whether anyone is using that somehow? (Reference Counting)
What if children keep bringing new stuff when you’re busy cleaning the room? Should you disallow them to use it while you’re busy cleaning? (Stop The World!)
Do you need help in figuring out what’s garbage and what’s not? (Mark Assist)
Being a lazy person that I’m, I won’t be able to write about everything in that greater detail. But just in case, if you feel I should, all you need to do is, just let me know.