I\'d like to create a thread that keeps track of the memory usage and cpu usage.
If the application reaches a high level, I want to generate an heap dump or a thread
In spring application, we can generate heap dump programmatically by creating cron job.
import com.sun.management.HotSpotDiagnosticMXBean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.management.MBeanServer;
import java.io.File;
import java.lang.management.ManagementFactory;
@Component
public class HeapDumpGenerator {
@Scheduled(cron = "0 0/5 * * * *")
public void execute() {
generateHeapDump();
}
private void generateHeapDump() {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
String dumpFilePath = System.getProperty("user.home") + File.separator +
"heap-dumps" + File.separator +
"dumpfile_" + System.currentTimeMillis() + ".hprof";
try {
HotSpotDiagnosticMXBean hotSpotDiagnosticMXBean = ManagementFactory
.newPlatformMXBeanProxy(mBeanServer,
"com.sun.management:type=HotSpotDiagnostic",
HotSpotDiagnosticMXBean.class);
hotSpotDiagnosticMXBean.dumpHeap(dumpFilePath, Boolean.TRUE);
} catch (Exception e) {
// log error
}
}
}
It will run at every five minutes, but we can set our own time/interval. We can also add condition before calling generateHeapDump() method.