当前位置:   article > 正文

java profile_一个java的Profile工具

java profile

/*** 性能相关的调试工具,支持,线程正式场景,做运行时间的profile,运行性能监控(不建议线上使用,因为需要开启监控线程)

* 该工具不会抛出任何异常

*@authorAdministrator

*@version$Id: ProfileUtils.java, v 0.1 2016年9月5日 下午11:02:45 Administrator Exp $*/

public classProfiler {/**debug模式*/

//private static volatile boolean debug = false;

private final static String LOG_TEMPLATE = "[messag=%s][startTime=%s][endTime=%s][durationTime=%sms][processors=%s][memUse=%s]";private final static String SIMPLE_LOG_TEMPLATE = "[durationTime=%sms][message=%s]";private final static SimpleDateFormat DATE_FORMAT = newSimpleDateFormat("yyyy/MM/dd HH:mm:ss");/**profile日志,建议运行中别做修改,否则有些配置会导致残留线程*/

private static ThreadLocal configHolder = new ThreadLocal() {protectedProfileConfig initialValue() {return newProfileConfig(false, false,0);

};

};/**开始monitor的时间*/

private static ThreadLocal> resStackHolder = new ThreadLocal>() {protected java.util.StackinitialValue() {return new Stack();

};

};/**监控线程*/

private static ThreadLocal monitorThreadHolder = new ThreadLocal();/*** 开始monitor*/

public static voidenter(Object msgObj) {try{

Stack monitorResStack =resStackHolder.get();

monitorResStack.push(newMonitorResource(msgObj, System.currentTimeMillis()));

ProfileConfig config=configHolder.get();//开启监控线程

if(config.isUseMonitorThread()) {if (monitorThreadHolder.get() != null) {

killThread();

}

MonitorThread monitorThread= newMonitorThread(getCurrentMonitorRes(), config);

monitorThreadHolder.set(monitorThread);

monitorThread.start();

}

}catch(Throwable e) {//if (debug) {//e.printStackTrace();//}

return;

}

}/*** 结束monitor

*@return

*/

public staticMonitorResource release() {try{

Stack monitorResStack =resStackHolder.get();

MonitorResource monitorResource=getCurrentMonitorRes();

monitorResource.setEndTime(System.currentTimeMillis());

ProfileConfig config=configHolder.get();//监控线程关闭

if(config.isUseMonitorThread()) {

killThread();

}returnmonitorResStack.pop();

}catch(Throwable e) {//if (debug) {//e.printStackTrace();//}

return new MonitorResource(e.getMessage(), 0);

}

}/*** 使用新的messageObj替换原来的

*@parammessageObj

*@return

*/

public staticMonitorResource release(Object messageObj) {

MonitorResource monitorResource=release();

monitorResource.setMessageObj(messageObj);returnmonitorResource;

}/*** 结束monitor并且打印日志

*@paramlogger

*@return

*/

public staticMonitorResource releaseAndLog(Logger logger, Object messageObj) {

MonitorResource resource=release(messageObj);

LoggerUtils.info(logger, resource);returnresource;

}/*** 结束monitor并且打印日志

*@paramlogger

*@return

*/

public staticMonitorResource releaseAndLog(Logger logger) {

MonitorResource resource=release();

LoggerUtils.info(logger, resource);returnresource;

}/*** 设置profile配置

*@paramconfig*/

public static voidsetProfileConfig(ProfileConfig config) {

configHolder.set(config);

}/*** Setter method for property debug.

*

*@paramdebug value to be assigned to property debug*/

//public static void setDebug(boolean debug) {//Profiler.debug = debug;//}

/*** 移除监控线程*/

private static voidkillThread() {try{

MonitorThread futureTask=monitorThreadHolder.get();

monitorThreadHolder.remove();

futureTask.interrupt();

}catch(Throwable e) {//ignore//if (debug) {//e.printStackTrace();//}

}

}/*** 获取当前的monitorRes

*@return

*/

public staticMonitorResource getCurrentMonitorRes() {try{

Stack resStack =resStackHolder.get();return resStack.get(resStack.size() - 1);

}catch(Exception e) {//if (debug) {//e.printStackTrace();//}

return new MonitorResource(e.getMessage(), 0);

}

}/*** 资源使用情况,比如cpu最大使用量等。

*@authorAdministrator

*@version$Id: Profile.java, v 0.1 2016年9月5日 下午11:38:39 Administrator Exp $*/

public static classMonitorResource {/**当前资源的标志*/

private Object messageObj = null;private long startTime = 0;private long endTime = 0;private int processorNums = 0;private List memUse =Lists.newArrayList();/***@parammessageObj

*@paramstartTime*/

public MonitorResource(Object messageObj, longstartTime) {super();this.messageObj =messageObj;this.startTime =startTime;

}/*** Setter method for property messageObj.

*

*@parammessageObj value to be assigned to property messageObj*/

public voidsetMessageObj(Object messageObj) {this.messageObj =messageObj;

}publicString getMemUse() {

StringBuilder stringBuilder= newStringBuilder();for (int i = 0; i < memUse.size(); i++) {

stringBuilder.append(memUse.get(i)/ 1024L + "K");if (i != memUse.size() - 1) {

stringBuilder.append(",");

}

}returnstringBuilder.toString();

}/*** 获取整个profile堆栈

*@return

*/

public StackgetMonitorResStack() {returnresStackHolder.get();

}/***@seejava.lang.Object#toString()*/@OverridepublicString toString() {returnconfigHolder.get().isUseSimpleLogTemplate()? (String.format(SIMPLE_LOG_TEMPLATE, endTime -startTime, messageObj))

: (String.format(LOG_TEMPLATE, messageObj, DATE_FORMAT.format(newDate(startTime)),

DATE_FORMAT.format(new Date(endTime)), endTime -startTime, processorNums,

getMemUse()));

}/*** 获取运行时间

*@return

*/

public longgetDurTime() {return endTime -startTime;

}public void putMemUse(longl) {

memUse.add(l);

}/*** Setter method for property endTime.

*

*@paramendTime value to be assigned to property endTime*/

public void setEndTime(longendTime) {this.endTime =endTime;

}/*** Getter method for property messageObj.

*

*@returnproperty value of messageObj*/

publicObject getMessageObj() {returnmessageObj;

}/*** Setter method for property processorNums.

*

*@paramprocessorNums value to be assigned to property processorNums*/

public void setProcessorNums(intprocessorNums) {this.processorNums =processorNums;

}

}public static classProfileConfig {private boolean useSimpleLogTemplate = false;private boolean useMonitorThread = false;private int monitorCollectDurTime = 500;/***@paramuseSimpleLogTemplate

*@paramuseMonitorThread

*@parammonitorCollectDurTime*/

public ProfileConfig(boolean useSimpleLogTemplate, booleanuseMonitorThread,intmonitorCollectDurTime) {super();this.useSimpleLogTemplate =useSimpleLogTemplate;this.useMonitorThread =useMonitorThread;this.monitorCollectDurTime =monitorCollectDurTime;

}/*** Getter method for property useSimpleLogTemplate.

*

*@returnproperty value of useSimpleLogTemplate*/

public booleanisUseSimpleLogTemplate() {returnuseSimpleLogTemplate;

}/*** Setter method for property useSimpleLogTemplate.

*

*@paramuseSimpleLogTemplate value to be assigned to property useSimpleLogTemplate*/

public void setUseSimpleLogTemplate(booleanuseSimpleLogTemplate) {this.useSimpleLogTemplate =useSimpleLogTemplate;

}/*** Getter method for property useMonitorThread.

*

*@returnproperty value of useMonitorThread*/

public booleanisUseMonitorThread() {returnuseMonitorThread;

}/*** Setter method for property useMonitorThread.

*

*@paramuseMonitorThread value to be assigned to property useMonitorThread*/

public void setUseMonitorThread(booleanuseMonitorThread) {this.useMonitorThread =useMonitorThread;

}/*** Getter method for property monitorCollectDurTime.

*

*@returnproperty value of monitorCollectDurTime*/

public intgetMonitorCollectDurTime() {returnmonitorCollectDurTime;

}/*** Setter method for property monitorCollectDurTime.

*

*@parammonitorCollectDurTime value to be assigned to property monitorCollectDurTime*/

public void setMonitorCollectDurTime(intmonitorCollectDurTime) {this.monitorCollectDurTime =monitorCollectDurTime;

}

}private static class MonitorThread extendsThread {private static final AtomicLong threadCount = newAtomicLong();privateMonitorResource monitorResource;private finalProfileConfig config;/****/

publicMonitorThread(MonitorResource resource, ProfileConfig config) {

monitorResource=resource;

setName("monitor-thread-" +threadCount.getAndIncrement());

setDaemon(true);this.config =config;

}/***@seejava.lang.Thread#run()*/@Overridepublic voidrun() {

monitorResource.setProcessorNums(Runtime.getRuntime().availableProcessors());while (true) {

monitorResource.putMemUse(

Runtime.getRuntime().maxMemory()-Runtime.getRuntime().freeMemory());try{

Thread.sleep(config.getMonitorCollectDurTime());

}catch(InterruptedException e) {//if (debug) {//e.printStackTrace();//}

return;

}

}

}

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/823468
推荐阅读
相关标签
  

闽ICP备14008679号