I have started with Java as my programming language and developed many applications in Java only (Ok, sometimes python) for 3 years. It is when I started my first official study in computer science, I realized there is a huge hue and cry about memory management. I started doing my college projects in C/C++, and realized, Uff !! I have to worry where my variables stay in memory and if they are not needed anymore, I have to free up space too. It is strange that till the time we face a problem, we never know that exists and it is handled for us (as Java handles it for us). This intrigued me into taking system classes in my college to get in-depth knowledge about how garbage(i.e. variables not used anymore) is collected in Java and how I coded carefree in Java for 3 years!
Ok, starting from scratch. You put int x=5. During the runtime i.e. execution of the program, this x is going to point towards a location of 4 bytes on the heap which has 5 as a value. You used this x in one line of your 1000 lines of code and then not use it anymore! What is scary to thing is that these 4 bytes are locked for a variable which is hardly used anymore in your program. Solution: Use lesser variables? Not possible: we know that these high-level programming languages are meant to give us the freedom to use whatever we want! That’s what helped to code and earn a living out of it despite never having any official education in computer science! Another solution: there should be some way that computer (in the very naive way) keep checking for these left /unused bytes in memory and keep deallocating them for us.
There are many algorithms/schemes which are used in mixed and match style to do this automatic cleaning for us. They deviate on various logics. Some of these logics answer the following questions. Ponder upon them before knowing these logics!
When to garbage collect?
As soon as a variable is not used.
When the memory is full i.e. when it is utterly needed to do it!
Once in a while.
Should we stop the allocation when garbage collecting?
Should the allocation be done in this way that garbage collecting is more efficient and cleaner?
Is there a pattern in the way objects stay alive/ useful?
I will try answering these questions with real implementations in my next blog. Till then Happy garbaging, oops I mean coding!
Orginally posted on : https://email@example.com/