-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGarbageCollectionExample.java
More file actions
41 lines (30 loc) · 1.13 KB
/
Copy pathGarbageCollectionExample.java
File metadata and controls
41 lines (30 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Day 29 - Memory Model and Garbage Collection
*/
public class GarbageCollectionExample {
static class LargeObject {
byte[] data = new byte[1024 * 1024];
}
public static void main(String[] args) {
System.out.println("=== Garbage Collection ===\n");
System.out.println("Before GC:");
System.out.println("Memory: " + Runtime.getRuntime().totalMemory());
// Create objects
LargeObject[] objects = new LargeObject[10];
for (int i = 0; i < 10; i++) {
objects[i] = new LargeObject();
}
System.out.println("After creating objects:");
System.out.println("Free memory: " + Runtime.getRuntime().freeMemory());
// Clear references
for (int i = 0; i < 10; i++) {
objects[i] = null;
}
System.out.println("After clearing references (before GC):");
System.out.println("Free memory: " + Runtime.getRuntime().freeMemory());
// Suggest GC
System.gc();
System.out.println("After GC:");
System.out.println("Free memory: " + Runtime.getRuntime().freeMemory());
}
}