1 package storm.scheduler; 2 3 import java.lang.management.ManagementFactory; 4 import java.lang.management.ThreadMXBean; 5 import java.util.HashMap; 6 import java.util.Map; 7 import java.util.Set; 8 9 import cpuinfo.CPUInfo; 10 11 /** 12 * 负载监视器 13 * @author wxweven 14 * @version 1.0 15 * @email [email protected] 16 * @blog http://wxweven.com 17 * @Copyright: Copyright (c) wxweven 2009 - 2016 18 */ 19 public class LoadMonitor { 20 21 private static final int SECS_TO_NANOSECS = 1000000000; 22 private static LoadMonitor instance = null; 23 private final long cpuSpeed; // Hz 24 Map<Long, Long> loadHistory; 25 26 public static LoadMonitor getInstance() { 27 if (instance == null) { 28 instance = new LoadMonitor(); 29 } 30 return instance; 31 } 32 33 private LoadMonitor() { 34 cpuSpeed = CPUInfo.getInstance().getCoreInfo(0).getSpeed(); 35 } 36 37 public Map<Long, Long> getLoadInfo(Set<Long> threadIds) { 38 // get current load 39 Map<Long, Long> currentLoadInfo = new HashMap<Long, Long>(); 40 ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); 41 for (long id : threadIds) { 42 currentLoadInfo.put(id, threadBean.getThreadCpuTime(id)); 43 } 44 45 // compute difference wrt history 46 Map<Long, Long> loadInfo = new HashMap<Long, Long>(); 47 for (long id : threadIds) { 48 // Long oldObj = (loadHistory != null)?loadHistory.get(id):0; 49 // long old = (oldObj != null)?oldObj.longValue():0; 50 long old = 0; 51 if (loadHistory != null && loadHistory.get(id) != null) { 52 old = loadHistory.get(id); 53 } 54 double deltaTime = (double)(currentLoadInfo.get(id) - old) / SECS_TO_NANOSECS; // sec 55 loadInfo.put(id, (long)(deltaTime * cpuSpeed)); 56 } 57 58 // replace history with current 59 loadHistory = currentLoadInfo; 60 61 return loadInfo; 62 } 63 }
时间: 2024-10-12 15:10:05