包中的代码com.sun.*
仅适用于 Sun/Oracle JVM,其他实现可能无法访问这些不属于官方 JDK 的专有类。本质上,Sun 添加了一些附加功能ThreadMXBean
(令人困惑的是并没有更改名称),但不想强制所有 JVM 实现都类似地实现此行为。
可能 Jenkins 不使用(或者你的配置不使用)Oracle 的 JVM。疯狂的猜测,但它可能正在使用 JRockit。
一般来说,您应该com.sun.*
在默认情况下假设类不可用的情况下实现代码,并且应该在运行时检查它们是否确实可用。例如,这是我目前如何处理该ThreadMXBean
问题的片段:
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.