I have a junit test cases with a class to monitor allocated bytes for a thread. From eclipse I was able to get the valid results. However in jenkins it's not working since com.sun.management.ThreadMXBean is not provided.
here's my code
((com.sun.management.ThreadMXBean)ManagementFactory.getThreadMXBean()).getThreadAllocatedBytes(Thread.currentThread().getId())))
How can get hold of com.sun.management.ThreadMXBean for I need to retrieve getThreadAllocatedBytes() ? how can i set the sun/oracle Vm right?
java.lang.ClassCastException: sun.management.ThreadImpl cannot be cast to com.sun.management.ThreadMXBean
Code in com.sun.*
packages are only available to Sun/Oracle JVMs, other implementations may not have access to these proprietary classes which aren't part of the official JDK. Essentially, Sun added some additional functionality onto ThreadMXBean
(and confusingly didn't change the name) but didn't want to mandate that all JVM implementations similarly implement this behavior.
Presumably Jenkins doesn't use (or yours is configured not to) Oracle's JVM. Wild guess, but it may be using JRockit.
Generally speaking, you should implement code assuming com.sun.*
classes are not available by default, and should check at runtime if in fact they are. For example, here's a snippet of how I'm currently handling the ThreadMXBean
issue:
private static boolean enableBeanInspection = true;
private ThreadMXBean tBean = null;
private com.sun.management.ThreadMXBean sunBean = null;
public ThreadInspector() {
// Ensure beans are null if we can't / don't want to use them
if(enableBeanInspection) {
tBean = ManagementFactory.getThreadMXBean();
if(tBean instanceof com.sun.management.ThreadMXBean) {
sunBean = (com.sun.management.ThreadMXBean)tBean;
}
if(tBean.isThreadCpuTimeSupported()) {
if(!tBean.isThreadCpuTimeEnabled()) {
tBean.setThreadCpuTimeEnabled(true);
}
} else {
tBean = null;
}
if(sunBean != null && sunBean.isThreadAllocatedMemorySupported()) {
if(!sunBean.isThreadAllocatedMemoryEnabled()) {
sunBean.setThreadAllocatedMemoryEnabled(true);
}
} else {
sunBean = null;
}
}
}
protected long getThreadTime() {
if(tBean != null) {
return tBean.getThreadCpuTime(threadId);
}
return -1;
}
protected long getThreadMemory() {
if(sunBean != null) {
return sunBean.getThreadAllocatedBytes(threadId);
}
return -1;
}
This defensive assume-we-don't-have-beans pattern lets you safely get as much information as the JVM will allow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With