2

Is there a way of finding the mapping between Java threads and POSIX threads on Linux for a multi-threaded application written in Java?

From my research, there is a 1:1 correspondence between each user-thread created in Java's OpenJDK and kernel threads via the NPTL. Assuming the above is correct, what would need to be done to hook into the JVM's native thread delegation mechanism to get each thread's POSIX id?

The motivation for getting each thread's id would be to inspect each thread's affinity, to get per-thread CPU times, and context-switch times at a specified sampling rate at runtime.

Although not a very experienced C/C++ developer, I would preferably like to write this in native code for learning purposes rather than using a more generic utility with a wider interface than what is necessary.

Any help is greatly appreciated.

GoofyBall
  • 401
  • 3
  • 8
  • 25

1 Answers1

0

Java threads are numbered from 1 to n. You could get a set of running Thread(s) with something like (based on an article hosted by nadeausoftware Java tip: how to list and find threads and thread groups).

static ThreadInfo[] getAllThreadInfos() {
    final ThreadMXBean thbean = ManagementFactory.getThreadMXBean();
    final long[] ids = thbean.getAllThreadIds();

    ThreadInfo[] infos;
    if (!thbean.isObjectMonitorUsageSupported()
            || !thbean.isSynchronizerUsageSupported())
        infos = thbean.getThreadInfo(ids);
    else
        infos = thbean.getThreadInfo(ids, true, true);

    final ThreadInfo[] notNulls = new ThreadInfo[infos.length];
    int nNotNulls = 0;
    for (ThreadInfo info : infos)
        if (info != null)
            notNulls[nNotNulls++] = info;
    if (nNotNulls == infos.length)
        return infos;
    return java.util.Arrays.copyOf(notNulls, nNotNulls);
}

public static void main(String[] args) {
    for (ThreadInfo t : getAllThreadInfos()) {
        System.out.printf("Thread %d, Name %s%n", t.getThreadId(),
                t.getThreadName());
    }
}
juzraai
  • 5,693
  • 8
  • 33
  • 47
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249