The document covers the concepts of Stack Memory and Heap Space in Java, detailing their characteristics, differences, and how memory is managed during method calls. It explains the process of passing objects to methods, including pass-by-value and pass-by-reference, as well as the role of the Java Virtual Machine (JVM) in memory usage and garbage collection. Additionally, it discusses generational garbage collection and how it operates to free up memory by removing unused objects.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
8 views56 pages
5_Stack Memory and Heap Space, Garbage Collection
The document covers the concepts of Stack Memory and Heap Space in Java, detailing their characteristics, differences, and how memory is managed during method calls. It explains the process of passing objects to methods, including pass-by-value and pass-by-reference, as well as the role of the Java Virtual Machine (JVM) in memory usage and garbage collection. Additionally, it discusses generational garbage collection and how it operates to free up memory by removing unused objects.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56
STACK MEMORY AND
HEAP SPACE, GARBAGE COLLECTION
Instructor: DieuNT1
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use
Agenda ▪ Stack Memory and Heap Space ✔Stack Memory? ✔Heap Space? ✔Stack Memory vs Heap Space ▪ Passing Objects to Methods ✔Value and Reference Parameters ✔Passing Objects to Methods ✔Array of objects ▪ JVM Memory usage ▪ Java Garbage Collection ✔What is Garbage Collection? ✔Generational Garbage Collection ✔How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 2
Section 1
Stack Memory and Heap Space
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 3
Introduction ▪ To run an application in an optimal way, JVM divides memory into stack and heap memory. ▪ Whenever we declare new variables and objects, call a new method, declare a String, or perform similar operations, JVM designates memory to these operations from either Stack Memory or Heap Space.
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 4
Stack Memory Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects that are in a heap, referred from the method.
▪ Key Features of Stack Memory
✔It grows and shrinks as new methods are called and returned respectively ✔Variables inside stack exist only as long as the method that created them is running ✔It’s automatically allocated and deallocated when method finishes execution ✔If this memory is full, Java throws java.lang.StackOverFlowError ✔Access to this memory is fast when compared to heap memory ✔This memory is threadsafe as each thread operates in its own stack
Access to this memory is in Last-In-First-Out (LIFO) order.
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 5
Heap Space Heap space in Java is used for dynamic memory allocation for Java objects and JRE classes at the runtime. New objects are always created in heap space and the references to this objects are stored in stack memory.
▪ Key Features of Java Heap Memory
✔If heap space is full, Java throws java.lang.OutOfMemoryError ✔Access to this memory is comparatively slower than stack memory ✔This memory, isn’t automatically deallocated. It needs Garbage Collector to free up unused objects so as to keep the efficiency of the memory usage ✔Unlike stack, a heap isn’t threadsafe and mory is relatively needs to be guarded by properly synchronizing the code
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 6
Stack Memory vs Heap Space ▪ Based on what we’ve learned so far, let’s analyze a simple Java code to assess how to manage memory here: class Person { int id; String name; public Person(int id, String name) { this.id = id; this.name = name; } } public class PersonBuilder { private static Person buildPerson(int id, String name) { return new Person(id, name); }
public static void main(String[] args) {
int id = 23; String name = "John"; Person person = buildPerson(id, name); } } 09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 7 Stack Memory vs Heap Space ▪ Let’s analyze this step-by-step: ✔When we enter the main() method, a space in stack memory is created to store primitives and references of this method. • Stack memory directly stores the primitive value of integer id. • The reference variable person of type Person will also be created in stack memory, which will point to the actual object in the heap. ✔The call to the parameterized constructor Person(int, String) from main() will allocate further memory on top of the previous stack. This will store: • The this object reference of the calling object in stack memory • The primitive value id in the stack memory • The reference variable of String argument name, which will point to the actual string from string pool in heap memory ✔The main method is further calling the buildPerson() static method, for which further allocation will take place in stack memory on top of the previous one. This will again store variables in the manner described above. ✔However, heap memory will store all instance variables for the newly created object person of type Person.
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 8
Stack Memory vs Heap Space
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 9
Section 2
Passing Objects to Methods
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 10
Method Parameters
• Parameters (also called arguments) is variable that declare in the method definition. 01
• Parameters are always classified as "variables" not "fields".
02 • Two ways to pass arguments to methods • Pass-by-value 03 • Pass-by-reference
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 11
Value and Reference Parameters ▪ Pass-by-value ✔Copy of argument’s value is passed to called method ✔In Java, every primitive is pass-by-value ▪ Pass-by-reference ✔Caller gives called method direct access to caller’s data ✔Called method can manipulate this data ✔Improved performance over pass-by-value ✔In Java, every object/arrays is (are) pass-by-reference
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 12
Passing Objects to Methods ▪ You can pass objects to methods: Passing an object is actually passing the reference of the object.
public class Test {
public static void main(String[] args) { Circle myCircle = new Circle(5.0); printCircle(myCircle); }
public static void printCircle (Circle c) {
System.out.println("The area of the circle of radius " + c.getRadius() + " is " + c.getArea()); } }
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 13
Passing Objects to Methods ▪ Passing objects passes their reference ✔c and myCircle refer to same object ✔Changes via c affect myCircle outside method
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 14
Passing Objects to Methods ▪ Example:
▪ What are output?
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 15 Array of objects ▪ Create arrays of objects: Circle[] circleArray = new Circle[10];
▪ Use for loop to initialize the circleArray:
for (int i = 0; i < circleArray.length; i++) { circleArray[i] = new Circle(); }
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 16
Array of objects ▪ Array of objects is array of references ▪ Accessing involves two reference levels: ✔circleArray references entire array ✔circleArray[1] references a Circle
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 17
Array of objects ▪ Example: public class TotalArea { public static void printCircleArray(Circle[] public static void main(String[] args) circleArray) { { System.out.printf("%-30s%-15s\n", "Radius", "Area"); Circle[] circleArray; circleArray = createCircleArray(); for (int i = 0; i < circleArray.length; i++) { printCircleArray(circleArray); System.out.printf("%f-30f%-15f\n", } circleArray[i].getRadius(), circleArray[i].getArea()); /** Create an array of Circle objects } */ System.out.println("———————————————————————"); public static Circle[] // Compute and display the result createCircleArray() { System.out.printf("%-30s%-15f\n", Circle[] circleArray = new "The total area of circles Circle[5]; is",sum(circleArray)); } for (int i = 0; i < circleArray.length; i++) { public static double sum(Circle[] circleArray) { circleArray[i] = new double sum = 0; // Initialize sum Circle(Math.random() * 100); for (int i = 0; i < circleArray.length; i++) } sum += circleArray[i].getArea(); return circleArray; return sum; } } } 09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 18 Section 3
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 19
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 20
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 21
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 22
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 23
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 24
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 25
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 26
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 27
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 28
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 29
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 30
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 31
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 32
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 33
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 34
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 35
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 36
JVM Memory usage
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 37
Section 4
Java Garbage Collection
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 38
What is Garbage Collection? Garbage collection is a key feature for developers who build and compile Java programs on a Java Virtual Machine (JVM). Java objects are created on the heap, when objects are no longer needed, the garbage collector finds and tracks these unused objects and deletes them to free up space. Without garbage collection, the heap would eventually run out of memory, leading to a runtime OutOfMemoryError. ▪ The basics of Java Garbage Collection ✔Garbage Collection in Java is the automated process of deleting code that’s no longer needed or used. This automatically frees up memory space and ideally makes coding Java apps easier for developers. ✔Automatic garbage collection means you don’t have control over whether and when objects are deleted. This is in contrast to languages like C and C++, where garbage collection is handled manually.
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 39
Generational Garbage Collection ▪ Java eden space ✔The eden space in Java is a memory pool where objects are created. ✔When the eden space is full, the garbage collector either removes objects if they are no longer in use or stores them in the survivor space if they are still being used. ✔This space is considered part of the young generation in the memory heap. ▪ Java survivor spaces ✔There are two survivor spaces in the JVM: survivor zero and survivor one. ✔This space is also part of the young generation. ▪ Java tenured space ✔The tenured space is where long-lived objects are stored. Objects are eventually moved to this space if they survive a certain number of garbage collection cycles. ✔This space is much larger than the eden space and the garbage collector checks it less often. ✔This space is considered the old generation in the heap.
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 40
How does Garbage Collection work Minor Garbage Collection ▪ Let us assume that there are already objects on the Eden space when we start (objects 01 to 06 marked as used memory) ▪ The application creates a new object (07) ▪ JVM tries to get required memory from Eden space, but there is no free space in Eden to accommodate our object and hence JVM triggers minor Garbage Collection
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 41
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 42
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 43
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 44
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 45
How does Garbage Collection work Second Minor Garbage Collection ▪ Let us assume that some time have passed and there are more objects on the Eden space now (objects 07 to 13 marked as used memory) ▪ The application creates a new object(14) JVM tries to get required memory from Eden space, but there is no free space in Eden to accommodate our object and hence JVM triggers second minor Garbage Collection
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 46
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 47
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 48
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 49
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 50
How does Garbage Collection work 13 more Minor Garbage Collection cycles later ▪ This keeps on repeating for each minor GC and the survivors are shifted between S0 and S1 and their age is incremented. Once the age reaches the "max age threshold", 15 by default, the object is moved to the "Tenured space"
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 51
How does Garbage Collection work
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 52