This discussion is archived
0 Replies Latest reply: Feb 22, 2010 4:25 AM by 843829 RSS

Thread CPU time measurement.

843829 Newbie
Currently Being Moderated
Hello,



I have a simple scenario where I want to measure the CPU time a Java Thread has already spent in kernel and user space.
I would like to do this within a native Library - I know already about the java.lang.management.ThreadMXBean interface.

Therefore, I wrote a simple native Lib (a Windows DLL) which makes a call to the WIN API GetThreadTimes() function.
In order to do this in Windows a Thread HANDLE is requierd.
That HANDLE is constructed via the WIN API function OpenThread().
In order to return a valid handle OpenThread() needs a valid Thread ID.
In my example that Thread ID is acquired within the "Java world" via Thread.getId() and passed through JNI to the library call.

Here is a small code example:
JNIEXPORT jlong JNICALL Java_GetCPUTime_cpuTime (JNIEnv * env, jclass clazz, jlong id) {
     HANDLE hThread;
     FILETIME creation, exit, kernel, user;
     long long tuser, tkernel;
     
     hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, (DWORD)id);

     if (hThread == NULL) {
          fprintf(stderr, "ERROR: OpenThread failed! \n");
          fprintf(stderr, "REASON: %d", (long)GetLastError());
          return (jlong)-1;
     }

     if (!GetThreadTimes(hThread, &creation, &exit, &kernel, &user)) { ... }

     tuser = 0;
     tuser = tuser & user.dwHighDateTime;
     tuser = tuser & user.dwLowDateTime;

     tkernel = 0;
     tkernel = tkernel & kernel.dwHighDateTime;
     tkernel = tkernel & kernel.dwLowDateTime;
     
     return (jlong)(tkernel + tuser);
}
Running the example leads to failure of the OpenThread() call with an Error Code 87 that means: ERROR_INVALID_PARAMETER !
Due to my investigations the problem occurs because OpenThread() cannot find a Thread with the specified ID.
Regarding this situation I assumed that the JVM internal Thread IDs are not mapped 1:1 to the OS Thread IDs.
Is that right?

Question: How is that mapping accomplished within the Sun HotSpot?
How is CPU Time measurement done via java.lang.management.ThreadMXBean?
How can I identify grab a certain Java Thread at native level ?
I've spent some time browsing the JDK6 sources, but I could not find the appropriate place at code that could give me more clarity about this.

I'm glad if anyone could give me a hint ?

Thank you in advance.

Vladimir

Edited by: Vladimir.Nikolov on Feb 22, 2010 4:23 AM

Edited by: Vladimir.Nikolov on Feb 22, 2010 4:24 AM