problem ?bug? with getThreadCpuTime on Linux 2.6 with NPTL
I don't know, if this is a bug or my misuse of this function.
Strange is, that this code works fine in Windows (I use XP) and does not in Linux (I tried both 2.6.10 and 2.6.14 on Debian with NPTL). It seems, the time measured in Linux is only against one JVM and in Windows within one JVM.
package main;
import java.lang.management.*;
publicclass Main
{
publicstaticvoid main(String[] args)
{
runMonitorThread();
runHeavyThread(Thread.NORM_PRIORITY);
runHeavyThread(Thread.NORM_PRIORITY);
runHeavyThread(Thread.NORM_PRIORITY);
}
publicstaticvoid runHeavyThread(int priority)
{
Thread thread =new HeavyThread();
thread.setPriority(priority);
thread.start();
}
publicstaticvoid runMonitorThread()
{
Thread thread =new MonitorThread();
thread.start();
}
}
class HeavyThreadextends Thread
{
publicvoid run()
{
int cycles = 10000000;
while(true)
{
for(int i = 0; i < cycles; ++i)
{
if(i % (cycles/10) == 0) Thread.yield();
}
System.out.println("ThreadId: "+getId());
}
}
}
class MonitorThreadextends Thread
{
privatefinal ThreadMXBean threadMXBean;
public MonitorThread()
{
threadMXBean = ManagementFactory.getThreadMXBean();
String supported ="JVM: isThreadCpuTimeSupported";
if(threadMXBean.isThreadCpuTimeSupported())
{
supported = supported.concat(" - true.");
threadMXBean.setThreadCpuTimeEnabled(true);
}
else supported = supported.concat(" - FALSE!");
System.out.println(supported);
supported ="JVM: isThreadContentionMonitoringEnabled";
if(threadMXBean.isThreadContentionMonitoringSupported())
{
supported = supported.concat(" - true.");
threadMXBean.setThreadContentionMonitoringEnabled(true);
}
else supported = supported.concat(" - FALSE!");
System.out.println(supported);
}
publicvoid run()
{
int threadId;
long time, meanTime, lastTime = 0, lastNanos = 0, nanos, meanNanos;
// only for testing
threadId = 8;
try
{
while(true)
{
sleep(1000);
time= threadMXBean.getThreadCpuTime(threadId);
meanTime= time - lastTime;
nanos= System.nanoTime();
meanNanos= nanos -lastNanos;
lastTime= time;
lastNanos= nanos;
System.out.println("Thread ID("+threadId+"): "+meanTime);
System.out.println("Nanotime:"+meanNanos);
System.out.println("Ratio:"+( meanTime / (float)meanNanos ));
}
}
catch(Exception exp)
{
exp.printStackTrace();
}
}
}

