Last active
January 23, 2017 16:12
-
-
Save vladimirdolzhenko/f9c255fe95fd26011add00572a21b899 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.management.ManagementFactory; | |
import javax.management.MBeanServer; | |
import javax.management.ObjectName; | |
/** | |
* @author vladimir.dolzhenko | |
* @since 2017-01-23 | |
*/ | |
public class ThreadID { | |
public static void main(String[] args) throws Exception { | |
System.out.printf("0x%016X", getTID(Thread.currentThread().getName())); | |
} | |
static long getTID(String threadName) throws Exception { | |
ObjectName objectName = new ObjectName("com.sun.management:type=DiagnosticCommand"); | |
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); | |
final String threadPrint = (String) mbeanServer.invoke(objectName, "threadPrint", | |
new Object[] {new String[] {}}, | |
new String[] {String[].class.getName()}); | |
final String threadPrefix = '"' + threadName + "\" "; | |
// look up for a line like: | |
// "main" #1 prio=5 os_prio=0 tid=0x0000000002349000 nid=0x8ec4 waiting on condition [0x000000000255e000] | |
for (String line : threadPrint.split("\n")) { | |
if (line.startsWith(threadPrefix)) { | |
final String tidPrefix = " tid=0x"; | |
final int st = line.indexOf(tidPrefix); | |
if (st > 0) { | |
final int end = line.indexOf(' ', st + tidPrefix.length()); | |
final String substring = line.substring(st + tidPrefix.length(), end); | |
final long tid = Long.parseLong(substring, 16); | |
return tid; | |
} | |
} | |
} | |
throw new IllegalArgumentException("no thread " + threadName); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment