Visitor :

May 4, 2009

How to get java cpu usage (jvm instance)


Getting cpu usage in java instance, that limits in executing java virtual machine, not os.


Have a look at the java class sun.tools.jconsole.SummaryTab.java in open JDK7 or source in web.(http://www.docjar.com/html/api/sun/tools/jconsole/SummaryTab$Result.java.html)

If you know JConsole, you know that cpu usages graph. that source is below.

354 private static class CPUOverviewPanel extends OverviewPanel {
355 private long prevUpTime, prevProcessCpuTime;
356
357 CPUOverviewPanel() {
358 super(getText("CPU Usage"), cpuUsageKey, cpuUsageName, Plotter.Unit.PERCENT);
359 getPlotter().setDecimals(CPU_DECIMALS);
360 }
361
362 public void updateCPUInfo(Result result) {
363 if (prevUpTime > 0L && result.upTime > prevUpTime) {
364 // elapsedCpu is in ns and elapsedTime is in ms.
365 long elapsedCpu = result.processCpuTime - prevProcessCpuTime;
366 long elapsedTime = result.upTime - prevUpTime;
367 // cpuUsage could go higher than 100% because elapsedTime
368 // and elapsedCpu are not fetched simultaneously. Limit to
369 // 99% to avoid Plotter showing a scale from 0% to 200%.
370 float cpuUsage =
371 Math.min(99F,
372 elapsedCpu / (elapsedTime * 10000F * result.nCPUs));
373
374 getPlotter().addValues(result.timeStamp,
375 Math.round(cpuUsage * Math.pow(10.0, CPU_DECIMALS)));
376 getInfoLabel().setText(getText(cpuUsageFormat,
377 String.format("%."+CPU_DECIMALS+"f", cpuUsage)));
378 }
379 this.prevUpTime = result.upTime;
380 this.prevProcessCpuTime = result.processCpuTime;
381 }
382 }



So. I made my own class to get java-cpu usage.
private void _getJavaRuntime() {
OperatingSystemMXBean osbean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runbean = (RuntimeMXBean) ManagementFactory.getRuntimeMXBean();
int nCPUs = osbean.getAvailableProcessors();
long prevUpTime = runbean.getUptime();
long prevProcessCpuTime = osbean.getProcessCpuTime();
try {
Thread.sleep(500);
} catch (Exception e) { }
osbean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long upTime = runbean.getUptime();
long processCpuTime = osbean.getProcessCpuTime();
if (prevUpTime > 0L && upTime > prevUpTime) {
long elapsedCpu = processCpuTime - prevProcessCpuTime;
long elapsedTime = upTime - prevUpTime;
javacpu = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * nCPUs));
} else {
javacpu = 0.001;
}
uptime = runbean.getUptime();
}

Rounding(Scaling) x postion of decimal point

To round x postion of decimal point, use BigDecimal.setScale().

double requestPerSecond = httpInfo.getRequestPerSencond();
BigDecimal reqPerSec =
new BigDecimal(requestPerSecond).setScale(2,java.math.BigDecimal.ROUND_HALF_UP);

setScale

public BigDecimal setScale(int scale,
int roundingMode)
Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation, the unscaled value must be divided (rather than multiplied), and the value may be changed; in this case, the specified rounding mode is applied to the division.
Note that since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper scale; the returned object may or may not be newly allocated.

Parameters:
scale - scale of the BigDecimal value to be returned.
roundingMode - The rounding mode to apply.
Returns:
a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.
Throws:
ArithmeticException - scale is negative, or roundingMode==ROUND_UNNECESSARY and the specified scaling operation would require rounding.
IllegalArgumentException - roundingMode does not represent a valid rounding mode.

Effective Java References

Screen
http://www.parleys.com/display/PARLEYS/Home#slide=1;title=Effective%20Java%20Reloaded;talk=18317360

Java one in 2006
http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-1512&yr=2006&track=coreplatform

http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1512.pdf

BCEL in java6








Java 6 have bcel packages, so I made interesting code to print "Hello World" every first-experience java developers have to meet.


There are no library have to include. That's my favorite!! 






BCEL tutorial is below web site.


























import com.sun.org.apache.bcel.internal.Constants;


import com.sun.org.apache.bcel.internal.generic.ArrayType;


import com.sun.org.apache.bcel.internal.generic.ClassGen;


import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;


import com.sun.org.apache.bcel.internal.generic.InstructionFactory;


import com.sun.org.apache.bcel.internal.generic.InstructionList;


import com.sun.org.apache.bcel.internal.generic.MethodGen;


import com.sun.org.apache.bcel.internal.generic.ObjectType;


import com.sun.org.apache.bcel.internal.generic.PUSH;


import com.sun.org.apache.bcel.internal.generic.Type;






public class SimpleHelloWorldBuilder {


public static void main(String[] args) throws Exception {


// public HellowWorld extends java.lang.Object


ClassGen classGen = new ClassGen("HelloWorld", "java.lang.Object", "", Constants.ACC_PUBLIC


| Constants.ACC_SUPER, null);


ConstantPoolGen constantPoolGen = classGen.getConstantPool();


InstructionList instructionList = new InstructionList();






// public static void main


MethodGen methodGen = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_STATIC, Type.VOID,


// (String[] args)


new Type[] {new ArrayType(Type.STRING, 1)}, new String[] {"args"}, "main", "HelloWorld", instructionList, constantPoolGen);






InstructionFactory instructionFactory = new InstructionFactory(classGen);


classGen.addEmptyConstructor(Constants.ACC_PUBLIC);




// System.out.println


ObjectType printStream = new ObjectType("java.io.PrintStream");


instructionList.append(instructionFactory.createFieldAccess("java.lang.System", "out", printStream, Constants.GETSTATIC));




// "Hello world!!"


instructionList.append(new PUSH(constantPoolGen, "Hello World!!"));


instructionList.append(instructionFactory.createInvoke("java.io.PrintStream", "println", Type.VOID,


new Type[] {Type.STRING}, Constants.INVOKEVIRTUAL));






classGen.addMethod(methodGen.getMethod());


instructionList.dispose();






classGen.getJavaClass().dump("build/HelloWorld.class");


}


}














After running this class, I can find "build/HelloWorld.class". 


By using jad, I can see the decompiled class.




// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.


// Jad home page: http://www.kpdus.com/jad.html


// Decompiler options: packimports(3) 


// Source File Name:   






import java.io.PrintStream;






public class HelloWorld


{






    public HelloWorld()


    {


    }






    public static void main(String args[])


    {


        System.out.println("Hello World!!");


    }


}








Good JMX References

http://java.sun.com/docs/books/tutorial/jmx/
http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html#gdjou
http://java.sun.com/javase/6/docs/technotes/guides/management/mxbeans.html
http://java.sun.com/j2se/1.5.0/docs/guide/jmx/index.html
http://blog.naver.com/PostView.nhn?blogId=pecman&logNo=110015624171
http://www.ibm.com/developerworks/library/j-rtm1/index.html
https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_JCP-Site/en_US/-/USD/ViewFilteredProducts-SimpleBundleDownload
http://lemonfish.egloos.com/4253102
http://www.chicdesign.co.kr/java/JMX/overview/appendixA.htm#wp1002189
http://chanwook.tistory.com/575
http://link.allblog.net/1228782/http://hanjava.net/call-151/2006/08/21/java%EB%A1%9C-physical-memory-%ED%81%AC%EA%B8%B0-%EC%95%8C%EC%95%84%EB%82%B4%EA%B8%B0/
http://link.allblog.net/14933961/http://judy98.tistory.com/entry/Creating-a-Custom-JMX-Client
http://link.allblog.net/15921220/http://adeveloper.tistory.com/107
http://link.allblog.net/12312721/http://bcho.tistory.com/entry/WebLogic%EC%97%90%EC%84%9C-Inflight-Transaction%EC%A7%84%ED%96%89%EC%A4%91%EC%9D%B8-%ED%8A%B8%EB%A0%8C%EC%A0%9D%EC%85%98-%EC%83%81%ED%83%9C-%EB%AA%A8%EB%8B%88%ED%84%B0%EB%A7%81-%ED%95%98%EA%B8%B0
http://weblogs.java.net/blog/emcmanus/archive/2007/05/making_a_jmx_co_1.html
http://weblogs.java.net/blog/emcmanus/
http://marxsoftware.blogspot.com/2008/08/remote-jmx-connectors-and-adapters.html
http://weblogs.java.net/blog/emcmanus/archive/performance/index.html
http://blogs.sun.com/jmxnetbeans/
http://forums.sun.com/forum.jspa?forumID=537
http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/download.jsp

MXBEAN
http://weblogs.java.net/blog/emcmanus/archive/2006/02/what_is_an_mxbe.html
http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/
http://weblogs.java.net/blog/emcmanus/archive/2006/11/a_real_example.html
http://blogs.sun.com/jmxetc/entry/how_to_retrieve_remote_jvm
http://blogs.sun.com/joel/entry/easily_modifying_and_rebuilding_jmx

ConcurrentModificationException in java collection object

When you meet java.util.ConcurrentModificationException, you may suspect your code about modifying collection for iterating.


Below code occur java.util.ConcurrentModificationException, because java code try to change arraylist for iterating.


// copy is arraylist.
for (MBeanConnection notiConnection : copy) {
MetaConnectionData data = notiConnection.getMetaConnectionData();
int index = Collections.binarySearch(newConnList, data, notiComparator);
if (index >= 0) {
notiConnection.remove(index);
removedIndexList.add(index);
newConnList.remove(data);
}
}

So, java code have to change not to modify for iterating, or you have to clone the collections to avoid modification using clone() method.


List removedIndexList = new LinkedList();
for (MBeanConnection notiConnection : copy) {
MetaConnectionData data = notiConnection.getMetaConnectionData();
int index = Collections.binarySearch(newConnList, data, notiComparator);
if (index >= 0) {
notiConnection.remove(index);
removedIndexList.add(index);
newConnList.remove(data);
}
}

// To avoid ConncurrentModification Error
for (Integer i : removedIndexList) {
copy.remove(i.intValue());
}

How to gain Calendar type to String type in java

public static String getYYMM() {
Calendar cal = new GregorianCalendar();
StringBuffer sb = new StringBuffer();
sb.append(cal.get(Calendar.YEAR));

int month = cal.get(Calendar.MONTH) + 1;
String mon = month < 10 ? "0" + month : "" + month;
sb.append(mon);

return sb.toString();
}

public static String getYYYYMMDD() {
Calendar cal = new GregorianCalendar();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
return format.format(cal.getTime());
}