private void updateStats ( ) { final ThreadMXBean bean = ManagementFactory . getThreadMXBean ( ) ; if ( bean . isThreadCpuTimeEnabled ( ) ) { // Update stats for all current threads final long [ ] ids = bean . getAllThreadIds ( ) ; Arrays . sort ( ids ) ; long totalCpuTime = 0L ; for ( long id : ids ) { long cpuTime = bean . getThreadCpuTime ( id ) ; if ( cpuTime != - 1 ) { totalCpuTime += cpuTime ; CpuUsage usage = threadCpuUsages . get ( id ) ; if ( usage == null ) { final ThreadInfo info = bean . getThreadInfo ( id ) ; usage = new CpuUsage ( id , info . getThreadName ( ) ) ; threadCpuUsages . put ( id , usage ) ; } usage . update ( cpuTime ) ; } } // Update jvm cpu usage, if possible we query the operating system mxbean so we get // an accurate total including any threads that may have been started and stopped // between sampling. As a fallback we use the sum of the cpu time for all threads found // in this interval. // // Total cpu time can be found in: // http://docs.oracle.com/javase/7/docs/jre/api/management/extension/\ // com/sun/management/OperatingSystemMXBean.html // // We use reflection to avoid direct dependency on com.sun.* classes. final OperatingSystemMXBean osBean = ManagementFactory . getOperatingSystemMXBean ( ) ; try { final Method m = osBean . getClass ( ) . getMethod ( "getProcessCpuTime" ) ; final long jvmCpuTime = ( Long ) m . invoke ( osBean ) ; jvmCpuUsage . update ( ( jvmCpuTime < 0 ) ? totalCpuTime : jvmCpuTime ) ; } catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) { jvmCpuUsage . update ( totalCpuTime ) ; } // Handle ids in the map that no longer exist: // * Remove old entries if the last update time is over AGE_LIMIT // * Otherwise, update usage so rolling window is correct final long now = System . currentTimeMillis ( ) ; final Iterator < Map . Entry < Long , CpuUsage > > iter = threadCpuUsages . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { final Map . Entry < Long , CpuUsage > entry = iter . next ( ) ; final long id = entry . getKey ( ) ; final CpuUsage usage = entry . getValue ( ) ; if ( now - usage . getLastUpdateTime ( ) > AGE_LIMIT ) { iter . remove ( ) ; } else if ( Arrays . binarySearch ( ids , id ) < 0 ) { usage . updateNoValue ( ) ; } } } else { LOGGER . debug ( "ThreadMXBean.isThreadCpuTimeEnabled() == false, cannot collect stats" ) ; } }
Update the stats for all threads and the jvm .