您的位置:首页 > 编程语言 > Java开发

javatest

2016-05-22 17:01 423 查看
package storm.scheduler;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cpuinfo.CPUInfo;

/**
* 负载监视器
* @author wxweven
* @version 1.0
* @email wxweven@qq.com
* @blog http://wxweven.com * @Copyright: Copyright (c) wxweven 2009 - 2016
*/
public class LoadMonitor {

private static final int SECS_TO_NANOSECS = 1000000000;

private static LoadMonitor instance = null;

private final long cpuSpeed; // Hz

Map<Long, Long> loadHistory;

public static LoadMonitor getInstance() {
if (instance == null) {
instance = new LoadMonitor();
}
return instance;
}

private LoadMonitor() {
cpuSpeed = CPUInfo.getInstance().getCoreInfo(0).getSpeed();
}

public Map<Long, Long> getLoadInfo(Set<Long> threadIds) {
// get current load
Map<Long, Long> currentLoadInfo = new HashMap<Long, Long>();
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
for (long id : threadIds) {
currentLoadInfo.put(id, threadBean.getThreadCpuTime(id));
}

// compute difference wrt history
Map<Long, Long> loadInfo = new HashMap<Long, Long>();
for (long id : threadIds) {
// Long oldObj = (loadHistory != null)?loadHistory.get(id):0;
// long old = (oldObj != null)?oldObj.longValue():0;
long old = 0;
if (loadHistory != null && loadHistory.get(id) != null) {
old = loadHistory.get(id);
}
double deltaTime = (double)(currentLoadInfo.get(id) - old) / SECS_TO_NANOSECS; // sec
loadInfo.put(id, (long)(deltaTime * cpuSpeed));
}

// replace history with current
loadHistory = currentLoadInfo;

return loadInfo;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: