2009-03-11 26 views

Respuesta

1

En Linux puede usar Runtime. exec() para ejecutar "tiempo de actividad" y evaluar el resultado. No hay una mejor manera en Linux, y no creo que haya una manera igualmente "conveniente" en Windows.

2

En Linux, puede leer el archivo/proc/loadavg, donde los primeros tres valores representan los promedios de la carga. Para Windows, probablemente tenga que apegarse a JNI.

5

Esto implica JNI pero hay una biblioteca GPL de Hyperic llamada Sigar que proporciona esta información para todas las plataformas principales, así como otras muchas otras estadísticas dependientes del sistema operativo, como el uso del disco. Funcionó muy bien para nosotros.

0

Si está utilizando el JRockit JVM puede usar JMAPI. Funciona para JDK 1.4, 1.5 y 1.6.

System.out.println("Total CPU-usage:" + JVMFactory.getJVM().getMachine().getCPULoad()); 

System.out.println("Total JVM-load :" + JVMFactory.getJVM().getJVMLoad()); 

for(Iterator it = JVMFactory.getJVM().getMachine().getCPUs().iterator(); it.hasNext();) 
{ 
    CPU cpu = (CPU)it.next(); 
    System.out.println("CPU Description: " + cpu.getDescription()); 
    System.out.println("CPU Clock Frequency: " + cpu.getClockFrequency()); 
    System.out.println("CPU Load: " + cpu.getLoad()); 
    System.out.println(); 
} 
4

getSystemLoadAverage() le da valor más de 1 minuto de tiempo (se actualiza cada segundo) y da este valor para el sistema operativo en general. Se debe realizar más información general en tiempo real al monitorear cada hilo por separado. También es importante tener en cuenta el intervalo de actualización de la monitorización: con mayor frecuencia se comprueba el valor, se mide más en un momento dado y si se realiza cada milisegundo, generalmente es 0 o 100 (o más dependiendo de cuántas CPU hay). Pero si permitimos un período de tiempo (por ejemplo, 1 segundo), obtenemos un margen en este período de tiempo y obtenemos un resultado más informativo. Además, es importante notar que es muy poco probable que solo un hilo ocupe más de una CPU (núcleo).

Después de la implementación permite utilizar 3 métodos:

  • getTotalUsage() - Carga total por todos los hilos en JVM
  • getAvarageUsagePerCPU() - carga Avarage por CPU (núcleo)
  • getUsageByThread (Rosca t) - Carga total por la rosca especificada

    import java.lang.management.ManagementFactory; 
    import java.lang.management.OperatingSystemMXBean; 
    import java.lang.management.ThreadMXBean; 
    import java.util.Collection; 
    import java.util.HashMap; 
    import java.util.HashSet; 
    import java.util.Map; 
    import java.util.Set; 
    
    public class MonitoringThread extends Thread { 
    
        private long refreshInterval; 
        private boolean stopped; 
    
        private Map<Long, ThreadTime> threadTimeMap = new HashMap<Long, ThreadTime>(); 
        private ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); 
        private OperatingSystemMXBean opBean = ManagementFactory.getOperatingSystemMXBean(); 
    
        public MonitoringThread(long refreshInterval) { 
         this.refreshInterval = refreshInterval; 
    
         setName("MonitoringThread"); 
    
         start(); 
        } 
    
        @Override 
        public void run() { 
         while(!stopped) { 
          Set<Long> mappedIds; 
          synchronized (threadTimeMap) { 
           mappedIds = new HashSet<Long>(threadTimeMap.keySet()); 
          } 
    
          long[] allThreadIds = threadBean.getAllThreadIds(); 
    
          removeDeadThreads(mappedIds, allThreadIds); 
    
          mapNewThreads(allThreadIds); 
    
          Collection<ThreadTime> values; 
          synchronized (threadTimeMap) { 
           values = new HashSet<ThreadTime>(threadTimeMap.values());  
          } 
    
          for (ThreadTime threadTime : values) { 
           synchronized (threadTime) { 
            threadTime.setCurrent(threadBean.getThreadCpuTime(threadTime.getId())); 
           } 
          } 
    
          try { 
           Thread.sleep(refreshInterval); 
          } catch (InterruptedException e) { 
           throw new RuntimeException(e); 
          } 
    
          for (ThreadTime threadTime : values) { 
           synchronized (threadTime) { 
            threadTime.setLast(threadTime.getCurrent());  
           } 
          } 
         } 
        } 
    
        private void mapNewThreads(long[] allThreadIds) { 
         for (long id : allThreadIds) { 
          synchronized (threadTimeMap) { 
           if(!threadTimeMap.containsKey(id)) 
            threadTimeMap.put(id, new ThreadTime(id)); 
          } 
         } 
        } 
    
        private void removeDeadThreads(Set<Long> mappedIds, long[] allThreadIds) { 
         outer: for (long id1 : mappedIds) { 
          for (long id2 : allThreadIds) { 
           if(id1 == id2) 
            continue outer; 
          } 
          synchronized (threadTimeMap) { 
           threadTimeMap.remove(id1); 
          } 
         } 
        } 
    
        public void stopMonitor() { 
         this.stopped = true; 
        } 
    
        public double getTotalUsage() { 
         Collection<ThreadTime> values; 
         synchronized (threadTimeMap) { 
          values = new HashSet<ThreadTime>(threadTimeMap.values());  
         } 
    
         double usage = 0D; 
         for (ThreadTime threadTime : values) { 
          synchronized (threadTime) { 
           usage += (threadTime.getCurrent() - threadTime.getLast())/(refreshInterval * 10000); 
          } 
         } 
         return usage; 
        } 
    
        public double getAvarageUsagePerCPU() { 
         return getTotalUsage()/opBean.getAvailableProcessors(); 
        } 
    
        public double getUsageByThread(Thread t) { 
         ThreadTime info; 
         synchronized (threadTimeMap) { 
          info = threadTimeMap.get(t.getId()); 
         } 
    
         double usage = 0D; 
         if(info != null) { 
          synchronized (info) { 
           usage = (info.getCurrent() - info.getLast())/(refreshInterval * 10000); 
          } 
         } 
         return usage; 
        } 
    
        static class ThreadTime { 
    
         private long id; 
         private long last; 
         private long current; 
    
         public ThreadTime(long id) { 
          this.id = id; 
         } 
    
         public long getId() { 
          return id; 
         } 
    
         public long getLast() { 
          return last; 
         } 
    
         public void setLast(long last) { 
          this.last = last; 
         } 
    
         public long getCurrent() { 
          return current; 
         } 
    
         public void setCurrent(long current) { 
          this.current = current; 
         } 
        } 
    } 
    
Cuestiones relacionadas