-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadMonitor.java
More file actions
82 lines (70 loc) · 3.08 KB
/
ThreadMonitor.java
File metadata and controls
82 lines (70 loc) · 3.08 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.thunder.novaapi.utils;
import com.thunder.novaapi.Core.NovaAPI;
import com.thunder.novaapi.config.NovaAPIConfig;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
public class ThreadMonitor {
private static final long CHECK_INTERVAL_MS = 10000; // 10 seconds
private static Thread monitorThread;
private static boolean running = false;
public static void startMonitoring() {
if (running) return; // Prevent multiple instances
running = true;
monitorThread = new Thread(() -> {
while (running) {
logAllThreads();
checkForDeadlocks();
try {
Thread.sleep(CHECK_INTERVAL_MS);
} catch (InterruptedException e) {
if (!running) {
NovaAPI.LOGGER.info("Thread monitor interrupted during shutdown (expected).");
Thread.currentThread().interrupt();
break;
}
NovaAPI.LOGGER.warn("Thread monitor interrupted unexpectedly", e);
}
}
}, "Nova-ThreadMonitor");
monitorThread.setDaemon(true); // Allow JVM to exit without waiting
monitorThread.start();
NovaAPI.LOGGER.info("✅ Nova API Thread Monitor started.");
}
public static void stopMonitoring() {
running = false;
if (monitorThread != null) {
monitorThread.interrupt();
}
}
private static void logAllThreads() {
if (!NovaAPIConfig.isMemoryThreadLogsEnabled()) {
return;
}
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
int threadCount = threadBean.getThreadCount();
NovaAPI.LOGGER.debug("📌 Active Threads: {}", threadCount);
if (NovaAPI.LOGGER.isTraceEnabled()) {
for (Thread thread : Thread.getAllStackTraces().keySet()) {
NovaAPI.LOGGER.trace("🧵 Thread Name: {} | ID: {} | State: {} | Priority: {}",
thread.getName(), thread.threadId(), thread.getState(), thread.getPriority());
}
}
}
private static void checkForDeadlocks() {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
long[] deadlockedThreadIds = threadBean.findDeadlockedThreads();
if (deadlockedThreadIds != null && deadlockedThreadIds.length > 0) {
NovaAPI.LOGGER.warn("⚠️ WARNING: Deadlocked threads detected!");
ThreadInfo[] deadlockedThreads = threadBean.getThreadInfo(deadlockedThreadIds);
for (ThreadInfo info : deadlockedThreads) {
NovaAPI.LOGGER.error("🚨 Deadlocked Thread: {} | State: {} | Lock Owner: {}",
info.getThreadName(), info.getThreadState(), info.getLockOwnerName());
}
} else {
if (NovaAPIConfig.isMemoryThreadLogsEnabled()) {
NovaAPI.LOGGER.debug("✅ No deadlocked threads detected.");
}
}
}
}