- Podcasts
- The Java Developers Hub
- Java Heap Memory Explained | Garbage Collection Algorithms & Memory Management Deep Dive
Java Heap Memory Explained | Garbage Collection Algorithms & Memory Management Deep Dive
The Java Developers Hub
- December 3, 2026
- 1 h 3 min
- Episode 20
About this episodeUnderstanding how Java manages memory is essential for building efficient, reliable, and high-performance applications. Java automatically…
In this episode, we take a deep dive into Java Heap Memory and explore how the Garbage Collector identifies and reclaims memory occupied by objects that are no longer reachable.
You'll learn how Java organises heap memory, understand different garbage collection algorithms, and discover how memory management affects application performance.
Whether you're an aspiring Java developer or an experienced software engineer preparing for advanced backend development, this tutorial will strengthen your understanding of Java memory management and runtime behaviour.
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Java Heap Memory Explained | Garbage Collection Algorithms & Memory Management Deep Dive
Also going to understand our garbage collection algorithms here. So again, you will have a lot of fun and learn a lot. As I told you, the topic of memory management is very important for the interview perspective as well as for writing optimized code. If you haven't seen its first video, then do watch the previous video so that you can understand it better. Let's quickly go to the screen and start. Yes, so in the previous video, we just talked about heap memory that it is a huge chunk of memory and in that chunk, our objects are declared. So let's say if I have made an object of student here, then it will go to our heap memory. If I have made an array, then it will also go to our heap memory. If I have declared a string, let's say hello, then it will also go to our heap memory. Now it depends whether I have declared a string using a new keyword or a string using a literal. If the string is of literal, then it will go to a special storage of heap memory, like hello, which I call string literal pool. Now it's time to understand the memory of our heap in depth. How the heap is divided and what are the parts in it. Our heap memory is divided into two parts. This is very interesting, understand this carefully. The first part is called the young generation. And the second part is called the old generation. So you can assume that if this is your heap memory, then it is divided into two parts.
Is young and old. Now let's divide it further. Our young generation is further divided into three parts. Let me make it like this. One is called Eden and these two are called Survivor Space. Now you must be wondering what is this? I will explain everything to you. For now, just understand the names. So I said that our heap memory is divided into two parts. First is the young generation and second is the old generation. And the young generation is divided into three parts. The first one is called Eden and the other two parts are called Survivor Space. Now you can take two names in this.
So let's say this is your S0. I will write in it that this is S0 and this is S1. And this outer part, the first part is Eden. Now why so many names? What's the use of them? Let me tell you why we divided the memory in this way. So let's make it clear. So this is the division of our heap memory. So we called it in two parts, young generation and old generation. We further divided the young generation into three parts, Eden, S0 and S1 and we call them survivor space. Now, obviously, there is another part of heap which we call string pool. You know that it is a part of heap memory. But look, I have made it a little different. Because now we are going to focus on our main heap, where we declare the.
We have already read about string pool separately in our string video. Now we are going to talk about our main heap memory. If you understand that it has so many parts, then let's understand why there are so many parts. Look, this is very simple, there were too many naming conventions. Whenever you declare any object in your code, let's say you had made a student class and you made an object of it, let's say student s1 equal to new student.
So, let's say you made this object of student type for the first time. So whenever you make a new object, let's say you made a new object of student type, it will go in heap memory in the Eden part. Right? So every object starts from the young generation in the starting and starts in the young generation in the Eden part.
But we write a lot of code just to do some small work. So basically, In Java's code, there are a lot of temporary objects whose life is very short. It is possible that they do a small work and then they finish. So, if we keep making such objects whose life is very short, then our heap memory.
In Eden many objects will die. Many objects will be dead. What does dead mean? You will stop referring them in your code. So if you stop referring them. Then garbage collection will run. It will declare those objects unreachable and remove them. So this is the meaning of saying. Because you have made this object fresh. So Java will say that I am not sure how long you are going to keep this object. So for now, I have put it in Eden, which is your first memory. After Eden, you have two survivor spaces S0 and S1. Now what happens is that as your object gets a little old, your object moves from Eden to S0 and then moves to S1. Now we will understand how it moves with the whole flow.
Now both S0 and S1 keep changing their place. Both of these are survivor spaces. So first it went to S0, then to S0, then to S1, then to S0, then to S1. And by doing this, your object will keep moving in the young generation up to a maximum frequency. Let's say we keep that maximum frequency 15 in your code. Basically, JVM says that until your garbage collection runs 15 times, your object will remain in the young generation if it is not dead. So, now suppose your object is not dead even after 15, after that we will pick up your object and move it into the old generation.
Now we will discuss why we kept it in young generation and then in old generation with an example. Now understand the big reason that when you make a new object then java is not sure. You will stop using that object as soon as possible. You will de-refer it as soon as possible. Right? So no reference variable will point it. So what I will do is, since I am not sure, I will divide the memory in two parts. One is young generation and the other is old generation. In the young generation, I will keep the newly created objects. I have divided them into 3 parts, Aden, S0 and S1. First of all, they will go to Aden. Garbage collection will run, even then your object will not be dead, then they will go to S0. Garbage collection will run again, your object will not be dead, then they will go to S1. And by doing this, they will keep rotating in S0 and S1 until a maximum frequency or throughput is attained, let's say 15. Once the number is attained that even after 15 times garbage collection, your object is not dead, then Java moves it to the old generation. Now the old generation means that your object is very old. So it has tolerated a lot of garbage collection scans, it has not been cleared yet. This means that the object you have created in your heap memory, let's say student's, it may have multiple reference variables pointing at it. It is difficult to de-refer it. Now you must be using it many times. So it can't clear the garbage collection directly. And to clear it means you have to remove all the reference variables from it. So in the old generation, the same variable or the same object is stored. who have tolerated the garbage collection scan many times but didn't clear it. That means JVM is sure that these objects are long-lived.
That's why in our old generation garbage collection is less frequently run but in our young generation garbage collection is run more frequently. Now you know that if garbage collection is run again and again then what will happen? Our program will get slow. We will discuss about this in the garbage collection algorithm. Why our program will get slow or stop. But if you assume that garbage collection is not good to run again and again. The more garbage collection is running, it means your program is getting slow. So we want it to run at least. That's why JVM has divided it into two memory. Where garbage collection will run slow, old generation. And where garbage collection will run again and again, which is young generation. Now, let's do it one by one and understand it with the flow. You will understand it better.
You have declared these four objects. Now, as you make these objects, where will all these objects go first? Into Eden space. Right? So, we have discussed that all our objects go into Eden space in the very beginning. So, you can assume that all these objects are here. Okay? Now, as you said above, in our young generation, your garbage collection runs more frequently.
Because Java is not sure how many objects are going to stay here. So, quickly, you have to remove the objects from memory. Now, garbage collection run in your young generation is called minor GC. Its algorithm is a little different, you will understand when we will study about GC You can understand its name, it is called Miner GC, which is the garbage collection that runs in the young generation Now Java will run the garbage collection, so JVM will run the garbage collection in the young memory As soon as the garbage collection runs, you know, we will see some of its algorithms, but what generally happens The objects that will be unreachable, it will remove them And the remaining objects will be moved from Eden.
Now what happens is, all the objects that survived Eden, so basically all the objects that are in Survivor Space, they get an age counter. So let's say, let me write it like this, we had two objects left, OB2. will have an age counter, let's say something like this. And similarly, OB4 will have an age counter, let's say something like this. So everyone gets their own age counter. So by default, since they have survived once, their age has become 1. Okay? Now let's assume that the garbage collection will run again. So after 2nd GC, garbage collection will run again. So let's say these two objects are still alive. OB2 and OB4 are still alive. So JVM will move them to the next survivor space. Which is called S1. So they moved to S1. And their age has been updated. This is 2 and this is 2. Something like this. Now what will happen? I will make it here. Let's say garbage collection runs for the 3rd time. So after 3rd GC. Let's assume that both the objects are saved, OB, 2B, and OB, 4B. Which means we are still using them in memory. So basically, Java moved them back to S0. Now they will keep changing, first from S0 to S1, then S1 to S0, S0 to S1, S1 to S0. So basically, they will keep roaming in the survivor space. And their age will keep getting updated. Now their age is 3. 3, 3, something like that. Now, how long will this keep happening? Until this age increases to a fixed number, which Java has already predetermined. So basically, their flow will go like this that they started from Eden, then they went to S0, then they went to S1, then they went to S0, then they went to S1, and so on, it will go on. Until a fixed number comes, after that they will escape into our old generation.
Now assume, after some number of times, let's say by doing this, we must have run this loop 15 times, right? So after 15th GC, After 15th GC In our garbage collection We could only survive one object Let's say OB2 OB4 was also deleted somewhere in the middle So OB2 could survive So JVM will move that OB2 into the old generation Into the old generation So this means that he must be 15 years old. He must be dead after 13. But he survived 15 garbage collection runs. That's why we moved OB2 to our old generation. Now, what's the special thing about old generation? If an object moves to old generation, what happens to it? The garbage collection runs in old generation is called Major GC. Major GC runs in old generation. Now, if this is our old generation, in which major GC runs, why is it special? What will be special about it? Java has made sure that the objects that live here, let's say our OB2 came here, so I stored OB2 here. The objects that live in our old generation are highly unlikely to be removed at once. So our garbage collection will run slowly. It will be run less frequently, comparatively our young generation. And because the objects here are very old objects, right? So, it is possible that they are pointed by a lot of reference variables. You can assume that as the object gets older. So, if you see here, there is an object called OB2 in the heap memory. And it has become very old. What does it mean by very old? In the program, garbage collection has been run 15 times. in our minor GC, basically in our young generation, even then it didn't get deleted, right? So, somewhere or the other, we will be using this object many times. So, I am saying, let's say, many reference variables, A, B, C, D, will point this in different situations, right? And everyone will use this. So in that case, the garbage collection that runs in the old generation has to be deep scanned to know which reference variables point to which object. Or if there is no other object in the heap memory that points to it. I told you that heap memory itself is like a big graph data structure. Because one object can point to another object.
Now obviously, the older your object is, the more chances it will have of having connections. So the garbage collection that runs here is very expensive. Expensive means it becomes very slow. That's why it runs at a low frequency. That's why we call it MajorGC. Because it will consume more memory, it will take more time to run. That's why Java says, what will I do to optimize it? I will run it from time to time. I will run it a little slow. Because I know that the objects here are already old. So there is a very low chance that it will get removed. So I will run them less frequently and see which objects I can remove from here.
Now suppose once the garbage collection is run here and our object has survived. No problem, now as soon as it has come in the old memory, it does not have any age factor. Age factor only works in our survivor space. Because Java has to see that when it will move directly in the old generation while jumping from here. If your object comes in old generation, then garbage collection will run timely. So let's say garbage collection runs once, OB2 is not cleared, no problem. Then it will run again, OB2 is not cleared, it will stay here, no problem.
For the third time, and this time OB2 can be cleared, then Java will clear it with memory. After that, if you make an object again, then it will start again from Eden. So you can understand that in our heap memory, every object starts its journey from Eden. After that it moves in survivor spaces and jumps in S0 and S1 periodically. And once it reaches a fixed number of counters, let's say 15 times, it shifts in our old generation. And this counter is incremented whenever a garbage collection runs. So as soon as a garbage collection runs, we move from Eden to S0, then S0 to S1, then S1 to S0, and so on. Once a fixed number of counter is run, let's say 15 times, we will move it to the old generation if it is not dead by then. Right? Now see, as I told you that the age counter is 15. So when garbage collection runs 15 times, then only our object will escape to the young generation and come to the old generation.
So see, it depends on many things that how much will be our age counter. So let's say it depends that our survivor space It's not getting overflowed. Survivor space overflow. It means that if you have created a lot of objects in your memory and our survivor space is full, then Java will quickly move some objects in the old generation. And let's say they are not even old, let's say their age counter has increased to 5 or 6, but still because our survivor space is getting full very soon, then Java will move them in the old generation. The second optimization that Java does is Dynamic Age Determination. What does it mean? If you declare a lot of objects in Java, then their age counter will also increase. So let's say a lot of age 5 variables are in our survivor space. So Java will understand that they are increasing again and again And there are a lot of them, so there is very little chance that you will delete all of them So Java will move them into the old generation So it also determines the dynamic age So let's say there is a fixed age, let's say 5 And a lot of objects are standing at 5 age Then all of them will shift to 6, then all of them will shift to 7 So Java will say that because you have made all of them together So they must have made them purposefully, maybe you are using them So JVM will shift all of them into the old generation And the third is that if you make a very large object Let's say you made an array of integer equal to new int and let's say you made it of 10 million size something like this. So what will happen if you declare such a big array, will it go to Eden first? Absolutely not because our space is limited. So what will Java say? Now if you have made such a big array, So it must have made it purposefully. Maybe you want to store so many integers. So JVM will directly move such a big object in our old generation. Basically here. So it will not put them in young and then in old. Because you have to optimize it. It knows that you have made such a big array. So JVM will directly move them in the old generation. I hope you understood the structure of the heap. Now in the last. Because we have read all our memories once. We have seen how our stack memory works. how our heap memory works, how our program counter and our method area works.
An example that will use all these well. So here I have taken an example of a student who has two variables name and age. One is static variable college which has iitg value. We have made its constructor and assigned its value here. Then we have made two methods in it. One is our normal instance method, mark attendance which does nothing. Our name is present. And one static method is change college. So change college takes a new string college and assigns it to our college variable.
JVM start, we write javac main.java as the file name is main and java main as we wrote java main, run the main class, jvm will start After that, we use class loader in JVM So we will load our main class in which we have our main method So we will load our main class first So where will the main class go after loading?
So let's say I write some information, we have a class, we have a main, let's say its parent is our object class because it doesn't extend to anyone else. Let's say it has a method, it has a main method and it takes a string type argument. So basically the class has all the metadata, there will be a lot more things in it, like which interface it implements. Now basically there will be a complete bytecode of the main, so let's say I write a bytecode here. And it will not be a complete bytecode, there will be some JIT compilation in it. And what is the access modifier of the main in it, for example, the main is public. Our main method is also public static, so there will be information of all this, etc. For now, I have added this information And I have said that this memory is called method area This is my method area So till now, when we were starting our code and started running So our main class, basically this class would have been loaded in our memory Right? That means our program counter So let's say I make my program counter something like this It will not store any instruction because we have not started executing the main method yet Till now, we have just loaded the main class Now when all this work is done, basically our main class is loaded in the method area, then our work number 3 will happen, which we know what will happen. So JVM will create our main thread, so let's say I write JVM creates main thread and that which is our main method, right, which we execute, which is our control flow from where it starts, it will load it in our stack frame, right. So JVM creates main thread and load main method in stack. So let's say I duplicate this so that I can see what's happening in the next page. And I start writing my next points from here. So this was my method area, this was my program counter. So now we made our main thread and loaded our main function in our stack space. So I also make my stack method in this way. Stack basically memory. So this will be my whole stack space. And here I have entered the main method. So my main method will load here. So I will write it as mainFrame. And all the things will come in it. So basically what is there in the main? There are arguments in the parameter. So args arguments have come here. Apart from that, what is there in the main? There is a reference variable called s1. So here s1 has come. Now it doesn't have any object. Right.
Okay. Okay. Now many times you will have a doubt that as we have made the main frame, we have already written that S1 is going to come, we already know the args from the parameters. Now how does java know that our local variable called S1 is going to come. He knows this by looking at the metadata of the class. Now think about it, the entry of the stack will be based on our metadata. So it must have seen the metadata carefully. Basically, the blueprint of the main class. What are the methods in it? So it took information about the main method. It took information about the local variables. And put them in the stack. So first of all, we will go to the stack, even though they haven't assigned any value yet. Value will be assigned when we will start executing the line one by one. For now, you can assume that it gets information from our method area. So when this point is done, then we start executing our main code. So let's say execute main. So now our main method will start executing line by line. First this line, then this line, then this line. And the program counter that we made here will point at these lines that where we are currently. So let's do one thing, let's make all our memory in one place. So I'll take this up too. So here I have kept all my memory together so that it will be easy for us.
Okay, so we have come to our fourth point that we have to start executing the main. So where will our main start executing? From the first line. So here it is written student s1 equal to new student aditya28. Now a lot is happening in this line. Let's understand one by one what will happen. Focus this line carefully. student s1 equal to new student aditya28. Now see, as soon as our program counter came in this line, basically to execute the first line, He saw that it was talking about a student object that we have to create a student object. But have I ever seen this student class before? The answer will be no, JVM has never seen it because in our metadata, no object named student or class named student exists. So first of all, our class loader will load this student class in our method area, right? Then only it will be able to create its object. So basically, one more entry will come in our method area. So I will write it, let's say class student Then we will get its instance fields. Now look at the student. This is our entire student class. Which fields does it have?
Now you know that in metadata itself, we store class variables or static variables. So here we will get college. They don't have any entry, they are all empty. Now this college is static filled, right? Its data will obviously be stored in the method area. But this name and age is just a part of the definition, right? It's a part of the signature. Here, actually, the name and age is not stored. The name and age will be stored in the heap memory itself. Because it is an instance variable and it is a part of the object. But here, we are just storing its signature that what will happen to the student. Okay?
Because the values of our static variable are also stored in the method area. We know that it is not stored in heap because static variable is a class level variable. These are common for all objects. So its value is also stored in the method area. So first of all, what will it do? Our college will give it a value. Now what is college? Think carefully.
So, will we store IITG directly here? Do we store string in the method area? The answer is no. We store string in the string pool. Because you see, we have basically used string literal while making this string. So, now imagine that we will have a heap memory. Okay, so I will make it like this. Now, I am not dividing it into young and old. You can understand from inside how it is. But in this heap memory, there will be a small part of ours, something like this, which I am calling our string pool. And our string hello will be inside this. And our college will point towards this string. Something like this. I hope you have understood that our college is stored here. But actually the string is stored in the string pool. So our college refers to the string of the string pool. When all this is done, now Java will implement this line in which it has written student s1 equal to new student. As soon as we use the new keyword, we will create a student type object in our heap memory. Let's say I have created a student object here. Now what variables do we have in that student object? what are our variables? We have name and age, which we call the instance variable. So these will also go inside our object. So here came the name, here came the age and by default they will get the initial value. So let's say the name got null in the starting because it is a string and the age got zero in the starting because it is an integer. Now there will be one more thing to think about Because we have passed Aditya in the constructor which is a string itself And all the strings go to the literal string pool So in our string pool, Aditya will also be there and it will also be stored there temporarily Even if we are not referring to it, it will be stored temporarily in our string pool We saw this in the string video too Because if we ever write a string in our code through a string literal Then it is stored in our string pool by default So now look, I can write the fifth point here. Our student object has been created. And they also got our initial values, name equal to null and age equal to zero. Now our constructor will be called. See, we have written new student here. And we are calling constructor. And Aditya and 28 are passing in that constructor. Now think carefully. Whenever we call constructor, where is our constructor? Here is our constructor. This constructor is also a method, right? We push it in our stack space, right? So this constructor will also be an entry in our stack space. So for now, what I will do is, I will make this reference a little I'll remove it from here. Okay, something like this. I've joined it from the bottom, our method area. Now, what I said is that this constructor will also be entered. So, I'll make the entry of this constructor, let's say something like this. So, this is our student constructor frame. So, I'll write student frame. This is our constructor call in the name of student. Now whenever you call a constructor or an instance method that is linked to an object, you know that all constructors are linked to an object, all instance variables are linked to an object, but static methods are not linked to objects, they are class type. So whenever you load a method that is linked to an object in your stack space, you will also get a reference of this. So as a local variable, this will also come here. This will be stored here because if you want to call any method or if you want to access any value from this student class, then you use this only.
So how will I reach this name which is in my heap memory. Using this keyword, I will say this, I will go inside this, this will point to this object. So as soon as I go inside this, I can go inside this object. and then I can also access the name and age. So basically, every instance method or constructor will have this reference.
And in constructor, obviously Aditya will be stored in the name, age will be 28. So I will write, here two variables will come, name and one will come, age. Aditya will be in the name, And let's say age will be 28. Something like this. Now see, what do we do in constructor? This.name equal to name, this.age equal to age.
So as soon as, you know who my this is pointing to. My this is pointing this object somewhere. So when I write this.name, I stand in front of this name, I say put value in this, whatever is in this name variable, so name is a local variable here, whatever has come in our stack space and where did we get that local variable, we got it from the constructor's parameter. So because the constructor's parameter had name and age both, so name and age will come in.
But the name and age written here, this is the instance variable written above us, above the student class. So these are our instance variables and these are our local variables. So the parameters that come are local and the ones that are inside our object are our instance variables. So I say put this.name inside whatever value is there in the name which is Aditya. So I will update my name here. So you know that here I will update Aditya. And if I update the age, it will be 28. Something like this. Now, the interesting thing is that here, will my aditya actually be stored?
So if a string is already made, we reuse it, we don't make it again. So what I mean to say is that the name will be referring to this AdityaName string, which will be in the string pool. And in age, 28 will normally be stored because it is a number. Okay, so till now our situation looks something like this. So first of all, we made our object, put our two variables in it, gave it a default value.
So when the constructor was run, its constructor made space in the stack memory. He declared the local variable there. Name became Aditya, age became 28. And what did he do? This.name is name, this.age is age. So we had the reference of this from here. So we reached here from this.name. We put the name in this basically Aditya. And we put 28 in this.age which was stored here. Now obviously the name will not be stored directly here Aditya. So that will also be referred in our string pool. In fact, the aditya we were storing here, will not be stored.
That means in our stack, the top space again took the main. Now our constructor is called. Object is created. Here new student used to come 28. And what is it doing? It is returning an object, a reference variable named S1. So basically here, the reference variable named S1 was stored till now. Now it will start pointing this object. I will remove this. So it will start pointing this object. Something like this. Now if this constructor is removed, then this reference will also be removed.
Right? Because our entire constructor is removed from our stack memory. So no one will be referring to it at any point. So now we have only 3 references. A reference variable named s1 refers to this object. Now the name here refers to the name in the string pool. And the string in our college refers to the string in our string pool.
With our reference variable s1, MarkAttendance method will call this object. But we know that the signature of any method is in the method area. So in the student class, the method area has a bytecode named markAttendance. So when we write s1. markAttendance, we are calling the markAttendance method. Which is this method, markAttendance. And as soon as we call it, this method will load in the stack memory.
So let's remove it from stack space because it is already used. So our constructor looks like this. Now I am loading mark attendance. So I have made a frame for it. This is the frame of mark attendance. Now, obviously, our mark attendance method is an instance method. So, it will also have a reference of this. So, here, a local variable like this will be stored, which will point this object temporarily. So, as long as our mark attendance method is there, this reference will also be there.
Okay. Now as soon as our program counter reached this line, we called mark attendance. Now if mark attendance is called, then our program counter will be updated and will come in this line. Basically in the first line of mark attendance. So here this mark attendance or all the push coming in our stack memory, they all store the return address so that when mark attendance is over and it goes back, then it can start from the next line of it. So it will also store its return address, which we will update in the program counter. Now we are not updating the PC anywhere, but you can assume that the current line number is stored by the PC. Okay, so we are not doing anything in this line, we are just printing on the screen, name is present. So when we will access the name, how will we access this.name? Now what is stored in this.name?
So we will just write on the screen, Aditya is present. Aditya is present and that's it, our work will be done. Something like this. So as soon as our line is executed, we will come back to our main method. That is, our mark attendance will pop up from the stack and we will start executing our next line. So basically our mark attendance has also left the stack space. That is, this reference variable is also not here, so I will remove it too.
And then as soon as I remove this from my stack memory, it gives me a return address, and from this, my program counter goes back to the last line. So now I just have to execute this last line, so student.collegename becomes iit-bombay. So I want to change iit-guhati to iit-bombay, and I want to update this.
Because I know that my changeCollegeName method, basically this method, This is my static method and I can refer it using class name. So I referred it like this. Now as we write student.changeCollege, this changeCollege method, whether it is an instance method or static method, first it has to be loaded in the stack frame. So I load it in the stack frame. and before that I remove my old method. So now my stack looks like this. Now I have loaded my changeCollege method. So here comes the changeCollege method. I have entered the entry here. Now will I have the reference of this here? There is no answer at all. Because my change college is not object specific. So there is no need to have a reference of this here. Whenever I have to access something, I will access it through my student class. And where is the student? In our metadata. So here I have a method named change college. I have written its name. It will take a string new college. So I can write it as NewCollege. And initially I am giving the value of NewCollege as IIT Bombay. So this NewCollege will store IIT Bombay. But again we will not put IIT Bombay in the stack space. We will put IIT Bombay again in our string pool. Now our string pool is filled so I am pointing it out. Let's say this is written in our string pool and our new college will refer to it. So let's make a reference string and it will point to our IIT Bombay. As soon as I put the method in my stack space, my program counter will shift to our next method So our program counter is now in this line And in this line we are doing college equal to new college Now which college is this talking about? This is talking about our static variable college And where does static variable college store? It stores in the method area This is the college. So, the college in the method area is pointing to IIT Guwahati right now. I am telling you to remove it from IIT Guwahati and point it to the one that is pointed to by the new college. Right? I have written this. College equal to new college. So, the one that is pointed to by the new college which is IIT Bombay, this college will also point to that.
And I will say that it will also refer me to IIT Bombay Something like this I hope you understood how our architecture looks like Now our method is over here, college equal to new college That means the program counter will want to come back That means this will be removed from the stack space again So we will do it again, remove I have removed it So that means the current reference will also be removed here So I will delete it So let's.
So let's remove it from the stack space. Now we don't have any space for it. So my stack space is empty again, there is only main method in it. So my heap memory looks like this, stack memory looks like this. The S1 in the stack memory is referring to this object. The name is referring to Aditya. And the college is referring to IIT Bombay. IIT Guwahati which is in my string pool is not being referred to. Garbage collection will be removed because it doesn't have any reference. Now finally, as soon as this line is executed, my program counter is updated, that is, my main method is also finished. So my main method will also be removed from the stack. So basically, I will remove this method from my stack space as well. Now as soon as the method is removed, you can understand that all these reference variables will also be removed.
Now when I am not pointing this object, then garbage collection will come And it will remove this too That means my heap will also be empty My stack will also be empty And method area will also be empty when my program stops running Okay I hope you understood There is a lot of mashup here, but I thought you must have got the idea. If you understood how all memory management works in Java, then now your memory management is clear. You have understood all types of memory, how it works. No one can stop you in an interview to explain how stack memory, heap memory, our method area and program counter work. If you understood, then now there is a very interesting topic about which very few people talk. And that is, types of references. What is a type of reference? See, it's a simple thing. Till now, we have simply told you that whenever you make an object, let's say student class, then you write like this. Student S1 equal to new student. And this was the only method that we used to discuss till now. Which I said that in heap memory, an object of student type will be created. And in your stack memory, a reference variable of S1 type will be created. And S1 will point it. This is what we were studying till now. See, this is absolutely correct. But we call this type of reference as strong reference. Strong reference. Okay. In fact, apart from this, there are many other references in Java like soft reference, weak reference, and phantom reference.
Let's say I told you that in Java, references are divided into four parts. One is called strong reference which we have been making till now. Whatever code we were writing was of strong reference. After this comes a soft reference. After this comes a weak reference. And the other one is phantom reference. Now look, the references here are in decreasing order of strictness.
Gone case means garbage collection has been removed from it. Now this garbage collection is used from inside. It is not that much of use for us. For us, it is mostly strong, weak and soft reference. In that too, 99% of the time, we use strong reference. Till today, we have never written a code in which we have made a reference other than this reference.
There are 1-2 situations where you may need them. So, let's understand that. Strong reference is a very simple thing. If I make an object, let's say, I am giving an example of strong reference. I have made an object student s1 equal to new student. So, whenever I make an object by doing something like this, So, I am making a strong reference.
You are saying that the student type object that I have made in my heap memory, garbage collection cannot remove it because I am pointing it in reference variable called s1. So, as long as I have any reference variable that points this object, garbage collection cannot remove it or mark it to remove it. Okay?
Now, one is your soft reference, which you make like this. You write in Java code, soft reference of type student. It uses generics, so you give student type here. Let's say, I call it S2, equal to new. Again, soft reference. Something like this. So what did you do here? So what did you do here? You made a soft reference of student type. So from inside things would be the same. That we would have an object of student type. And in the stack there would be a reference variable called s2. Which would point this object. But this reference variable is a soft reference this time. So soft reference tells our garbage collection. Keep this object in memory until you don't need it. So basically garbage collection will run. If it thinks that it has a memory requirement, then it will remove this object. But if it thinks that it doesn't have a memory requirement, then it will.
Is there any specific use case? Or is it just a name? Think about it. If you are implementing a cache, then you will prefer making a soft reference. Because what does cache mean? We store the frequently used data separately. So that whenever we need that frequently used data, we can return it. But the best thing about cache is that we don't make it infinite. It also ends. So if we use this soft reference as a cache, then as soon as our JVM needs space, our garbage collection needs space, it will clear this object. We say that our cache has cleared the data, which we call cache miss in programming terms. In that case, we will fetch the data again from the database and we will have to put the data in the cache again. So you can assume that if we want to implement the cache, soft references are very useful in that case. Now, our weak references are even more weak than this. And how do you make it? Obviously, you write weak reference of type student. Let's say you made s3 equal to new weak reference. Something like this. Again, the same thing happens from inside. Here, what did you do this time? You made an object called S3 and pointed it at our student object. But this reference this time is a weak reference. And a weak reference is so weak that you tell the garbage collection to let this object remain until the cycle of the next garbage collection runs. So basically weak references can't bear the next garbage collection. As soon as the garbage collection runs, this object will be removed. So this will remain in that memory until our garbage collection runs. Soft reference used to say that don't remove it until there is no need for memory. Remove it if there is a need. Our strong reference used to say that whether there is a need or not, you can't remove this object until I'm referring to it. But weak reference says that whenever you run the next cycle of garbage collection.
We read that we have a weak hash map in java. Right? In that case, weak reference is used. So again, it's a very specific use case. There are only a few algorithms in which you can use it. In fact, you can use it to implement cache. But again, the cache here will miss more data. Because as soon as garbage collection runs, our cache will be empty. Right?
That when there is a memory requirement, our object gets cleared. Right? Now the fourth is our phantom reference. In fact, we don't make it ourselves. Phantom reference means that the object is already cleared. So basically, when you get the object of phantom reference, if you make S4 of type phantom reference, then you will always get null. You will never get object. That means our object never stores phantom reference. Just assume that phantom reference uses garbage collection internally to calculate when I actually have to remove it. Now what does garbage collection do? Garbage collection doesn't remove an object directly. We will see in its algorithms. First it marks an object that it is ready to be removed. And then it removes it. So it uses phantom reference from inside. I have to remove it as less as I have to calculate it. So it gives phantom reference. When we will see the algorithms of garbage collection, you will understand better. These are the four types of references in java. Very few people talk about it. But it is very interesting. If someone asks you this, you can explain it well. Now let's move towards our end topic, which is again very interesting. And that is garbage collection algorithms. Garbage collection. So look, what is garbage collection? We know that it works to clear data in heap memory. Now how does it clear it? Here we have three big algorithms. The first and most common algorithm is the Mark and Sweep algorithm. After that is the Mark Compact algorithm. And one is Copying Algorithm. These are the three most common algorithms. We'll see what we use in modern Java today. First, let's understand about these three. It's very easy. Mark and Sweep is the most common and basic algorithm. It removes objects in the simplest way. So, Mark and Sweep. Let's say there are many objects in your heap. So let's say one object is A, one is B, one is C, one is D and one is E. So I have made 5 objects here which will be in our heap memory. Mark and Sweep works in two steps. First of all, it does marking and then sweeping. Marking means that our garbage collection goes through all these objects one by one and sees which are the objects that are not reachable. Basically, no reference variable points them. So basically, it marks them for sweeping. Sweeping means to remove the garbage and swipe it out. So let's say garbage collection runs here and it marks them. So let's suppose he found out that A is reachable, C is reachable, and E is reachable. B and D are not reachable. So basically he has just marked them. So specifically, he marked the reachable ones as reachable, and B and D are unreachable. Now once he marked them, in the second step he will do sweeping. So he swiped out the unreachable ones, B and D. Now A is left in our heap memory, B is removed, C is left, D is removed, and E is left. Something like this. So this was a very simple algorithm. It works in two steps. First it marks and then it sweeps. It marks which objects are reachable and removes the unreachable ones. And those objects are removed and the rest of the objects remain in our heap memory. Now you know the structure of the heap. It moves from Eden to 0, 0 to S1 etc. But this mark and sweep algorithm is a major part of GC. Our mark and sweep algorithm is run in our old generation.
Now the disadvantage of this algorithm is that it leaves fragmentation in between. So see, it removed B and D, its space remained here, it is unutilized. So you can consider it as an array, that basically what it did was, here there were array elements A, B, C, D, E, it removed B and D, but the space of this array remained unutilized. So our memory became fragmented. So basically it leaves a gap in memory, so it is a bit unoptimized. Now, to optimize this algorithm, a second algorithm came, which is like its elder brother, which is Mark and Compact, which says that I will do exactly the same thing.
Objects that are reachable So A is reachable, C is also reachable, E is also reachable And B and D are unreachable It has marked them once Now after that, when it swipes them out It will also compact the memory So basically now my memory will look like this A Then C will come here and then E will come here So the space of B and D that was left empty It removed the space and compacted it So as you can see in the array with elements It shifted the elements left and right one by one The advantage of this is that there is no fragmentation. But there is a disadvantage too. When you move the memory, it is a costly operation. Like I told you in the array that if you shift only one element to the left, it is a costly operation. Similarly, when you move the object in the heap, it is a costly operation. So I can write moving object is costly. Now this is also run in our old generation or major GC because both the algorithms are almost the same. Now the third algorithm that we talked about is Copping. And this specific algorithm is for the minor GC, basically for the young generation. What does it do? It is very simple. Let's say it starts from Eden. There are four variables in Eden. There are four objects A, B, C, D.
It just copies the reachable ones on the next step. So let's say our next step is S0. It found out who is reachable from A, B, C, and D. So it found out that only B and D are reachable. So it copied them in the next step and removed everything in the previous step. Because A and C were unreachable anyway. B and D are copied here. So it can remove all of them from Eden. Right? Same when it will shift from S0 to S1 It will copy all the objects that are not dead from B and D Let's say both of them are not dead So it copied B and D here And removed them from S0, something like this Now because there is no 2 step process like marking or sweeping And obviously our objects are not that complicated because they need deep search Most of our objects are new created So it doesn't take that much time to scan So our algorithm is very optimized It runs very fast and it runs in our Miner GC So these are all the algorithms of our garbage collection Now listen to an interesting problem here Garbage collection is a very special thing So in the Java community, all developers are told as a joke When garbage collection runs, it stops the world Stop the world What does it mean? In fact, a very famous word is STW Basically, stop the world What I mean to say is, let's suppose this is your program code.
So this is what STW basically says, stop the world, that whenever garbage collection runs, your application code stops completely. It stops executing. That's why I said in the beginning that if your garbage collection runs again and again, then your program will be very slow because it will stop its execution again and again. Okay, now the most interesting question, if we think from the first thought principle, that when the garbage collection runs, then why does the program stop? Because you think, garbage collection itself is an expensive operation, it will have to see all the objects, it will have to deep scan, now there is a lot of heap memory, there are a lot of objects made in it, and their graph is made, who points to whom, and a lot of variables in the stack will point to someone, etc.
Now, if your program is running, then it may create some new objects or change the references of some old objects. So garbage collection doesn't want this, it wants that when I am running, the graph that I have imagined, let me work on that. Let me work on those references, let me see which object I can delete and which I can't delete. Once I finish my work, after that you can start executing your program again. You can allocate new objects, use them, etc. So that the garbage collection runs properly, JVM stops our program completely to execute until GC is running. That's why Java has a saying, when garbage collection runs, it stops the world. The whole world stops, your entire program stops as it is, and our garbage collection only runs.
You must be declaring such objects that have a lot of references and those references will never be removed. Let's say they are on a global level or they are statically declared, so they are in the method area and they never delete references. Like there can be a lot of scenarios where your memory is getting leaked And your heap memory is getting full In that case your garbage collection will run again and again And your program will be very slow. Now modern java made this a little faster using parallel gc. So till now in old java we used sequential gc. What does sequential gc mean? It basically used a single thread to run. Parallel gc will use multiple threads to run. The advantage of this is that because it is using multiple threads, it can run parallel and can be executed concurrently. So it will end soon. That means our world will stop for a short time. Our program will stop for.
Program can't run if garbage collection is running. Even if it is for a short period of time, the garbage collection will definitely stop our program. So basically, you can run your garbage collection at least by writing good code. That is, you can optimize your program more. You can never stop the world. If the garbage collection runs, your world will stop.
Before this, Java was considered a very slow language because our runtime is slow due to garbage collection. Since it comes from parallel G, it stops for a very short time. So it becomes negligible for us. Okay, I hope you enjoyed it. Now, let me tell you one more interesting thing. If you want to run garbage collection on your own, then Java has given you a command. In fact, your system class has a method called.
So, if you call a static method gc in the system class, then you want to tell JVM to run garbage collection. But do you know what is interesting? Even if you write this, there is no guarantee that garbage collection will run. It depends on JVM because the entire garbage collection comes under JVM So it depends on that although you have written it You have requested it that I want the garbage collection to run now If JVM feels that it can run, if the things are optimized then it will run And it may not be able to run, it will be very expensive to run now, so it will not run But you basically, Java So this is basically, there is no guarantee but you can request from JVM To run the garbage collection by doing system.gc we have the command In fact, when I told you that our memory gets leaked due to which garbage collection is run again and again So when you know that our memory will get leaked, what error will we get? We will get out of memory error If our entire heap memory gets full, we will get out of memory error So basically there is no space left in my heap to create more objects And my garbage collection is also not able to remove any old objects because I am not de-referring anyone I am referring everyone In that case, I have something which I call heap dump This is a bit of an advanced concept. What we do in this is, basically, heap dump is nothing. Consider it as a screenshot or a snapshot of the entire heap memory. You say, take a screenshot of the current heap memory. And tell me which object is interacting with whom. So now you, You can use some software like Visual VM. Through this, you can study your heap memory. Which object is taking the most space? Which objects are linked to which objects? So that you can manually improve your code. This is a very interesting concept to optimize your code. If you know that you can get an error, then fine. I hope you understood everything well. You must have learned a lot. That's all in memory management. See you in the next video. Till then, thank you so much.
