AEM – Check Thread CPU Usage

Following AEM Groovy script will be very helpful during the performance issue diagnosis –

//threadsCpuUsage

sampleTime = 10_000
topThreads = 3

cores = Runtime.getRuntime().availableProcessors();
threadMxBean = java.lang.management.ManagementFactory.getThreadMXBean()
threadCpuInitialTimes = [:]
threadCpuElapsedTimes = [:]
stackTraces = [:]
threadMxBean.dumpAllThreads(false, false).each { info ->
threadCpuInitialTimes.put(info.threadId, threadMxBean.getThreadCpuTime(info.threadId))
}
try { Thread.sleep(sampleTime) } catch (all) {}
Thread.getAllStackTraces().each { thread, ste -> stackTraces[thread.id] = ste }
threadMxBean.dumpAllThreads(false, false).each { info ->
def startTime = threadCpuInitialTimes[info.threadId]
if (startTime != null) {
def elapsedCpu = threadMxBean.getThreadCpuTime(info.threadId) – startTime
def cpuUsage = elapsedCpu / (sampleTime * 1000000F);
threadCpuElapsedTimes[info] = cpuUsage
}
}
def i = 0
threadCpuElapsedTimes.sort { -it.value }.each { info, time ->
println String.format(‘%.2f’, 100 * time) + “\t” + info.threadId + “\t” + info.threadName

def ste = stackTraces[info.threadId]
if (i++ < topThreads && ste != null) {
ste.each { println “\t” + it }
println “”
}
}

true

 

 

Leave a comment