-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryAnanlyzer.java
More file actions
53 lines (44 loc) · 1.65 KB
/
Copy pathMemoryAnanlyzer.java
File metadata and controls
53 lines (44 loc) · 1.65 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MemoryAnanlyzer {
static class MemorySnapshot {
long used;
long committed;
long max;
public MemorySnapshot(long used, long committed, long max) {
this.used = used;
this.committed = committed;
this.max = max;
}
@Override
public String toString() {
return "Used: " + used + " | Committed: " + committed + " | Max: " + max;
}
}
public static MemorySnapshot fetchAndLogMemory() {
try {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heap = memoryBean.getHeapMemoryUsage();
long used = heap.getUsed();
long committed = heap.getCommitted();
long max = heap.getMax();
return new MemorySnapshot(used, committed, max);
} catch (Exception e) {
e.printStackTrace();
return null; // or any default value indicating failure
}
}
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(() -> {
MemorySnapshot snapshot = fetchAndLogMemory();
if (snapshot != null) {
System.out.println(snapshot);
}
}, 0, 10, TimeUnit.SECONDS);
}
}