Java objects can be stored in heap memory. It can be handled by JVM (Java Virtual Memory).
How it will be created???
Whenever a
new object is created using ‘new’ keyword, the memory is allocated the space in
heap.
As java has a garbage collector, it easily deallocates the
memory. To perform the efficient garbage collection, heap is divided into
different generations.
Young Generation: It deals with new objects.
Old Generation: when an object survived in multiple garbage
collection cycles, it is considered as old generation.
Permanent Generation : It has the metadata in older
versions. Now, it is considered as Meta space.
Java Program to illustrate Heap Memory:
public class GenerationalHeapEg {
public static void
main(String[] args) {
// A varible
is initialised with 0 value for iteration
int iter = 0;
// Loop to
create objects using the iteration variable
while (true) {
iter++;
createObjects(iter);
// to view the process,make the threas to
sleep
try {
Thread.sleep(100);
} catch
(InterruptedException e) {
e.printStackTrace();
}
//current iteration is displayed
System.out.println("Current Iteration is displayed here: " +
iter);
}
}
// A method is
created
private static
void createObjects(int iter) {
// for loop to
create the new objects
for (int i =
0; i < 10; i++) {
// Object
creation
new
Object();
}
// Display the
iteration
System.out.println("Created 10 objects in iteration: " +
iter);
}
}
Output:
C:\raji\blog>javac GenerationalHeapEg.java
C:\raji\blog>java GenerationalHeapEg
Created 10 objects in iteration: 1
Current Iteration is displayed here: 1
Created 10 objects in iteration: 2
Current Iteration is displayed here: 2
Created 10 objects in iteration: 3
Current Iteration is displayed here: 3
Created 10 objects in iteration: 4
Current Iteration is displayed here: 4
Created 10 objects in iteration: 5
Current Iteration is displayed here: 5
Created 10 objects in iteration: 6
Current Iteration is displayed here: 6
Created 10 objects in iteration: 7
Current Iteration is displayed here: 7
Created 10 objects in iteration: 8
Current Iteration is displayed here: 8
Created 10 objects in iteration: 9
Current Iteration is displayed here: 9
This is the way of implementing the java program to
illustrate heap memory.Keep Coding!!!
No comments:
Post a Comment