4

我有一个带有类的 junit 测试用例来监视线程的分配字节。从eclipse我能够得到有效的结果。但是在 jenkins 中它不起作用,因为没有提供 com.sun.management.ThreadMXBean 。

这是我的代码

((com.sun.management.ThreadMXBean)ManagementFactory.getThreadMXBean()).getThreadAllocatedBytes(Thread.currentThread().getId())))

如何获取 com.sun.management.ThreadMXBean 因为我需要检索 getThreadAllocatedBytes() ?我怎样才能正确设置太阳/甲骨文虚拟机?

java.lang.ClassCastException:sun.management.ThreadImpl 无法转换为 com.sun.management.ThreadMXBean

4

3 回答 3

5

包中的代码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.

于 2013-03-08T06:55:14.543 回答
0

我只是用

ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

不自暴自弃。你有同样的尝试吗?

于 2012-12-14T10:41:38.380 回答
-1

It appears that the execution was somewhat running on a jvm that doesn't support ThreadMXBean . In my ant configuration I added fork to a new thread. It worked great.

于 2013-06-03T12:02:34.780 回答