Skip to content

Instantly share code, notes, and snippets.

@paksv
Created May 5, 2014 12:56
Show Gist options
  • Save paksv/a6348b18cf4588ab7417 to your computer and use it in GitHub Desktop.
Save paksv/a6348b18cf4588ab7417 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import sun.jvm.hotspot.debugger.Address;
import sun.jvm.hotspot.oops.*;
import sun.jvm.hotspot.runtime.JavaThread;
import sun.jvm.hotspot.runtime.Threads;
import sun.jvm.hotspot.runtime.VM;
import sun.jvm.hotspot.tools.Tool;
public class PrintThreadIds extends Tool {
public static void main(String[] args) {
PrintThreadIds tool = new PrintThreadIds();
tool.start(args);
tool.stop();
}
@Override
public void run() {
List<ThreadInfo> infos = ThreadUtils.getAllThreadInfos();
for (ThreadInfo info : infos) {
System.out.printf("Thread@%s: tid=%d nid=0x%x\n",
info.getAddress(), info.getTid(), info.getNid());
}
}
public static class ThreadUtils {
public static List<ThreadInfo> getAllThreadInfos() {
List<ThreadInfo> infos = new ArrayList<ThreadInfo>();
Threads threads = VM.getVM().getThreads();
for (JavaThread thread = threads.first(); thread != null; thread = thread.next()) {
Address address = thread.getAddress();
long tid = getTid(thread);
long nid = Long.parseLong(thread.getThreadProxy().toString());
infos.add(new ThreadInfo(address, tid, nid));
}
return infos;
}
public static long getTid(JavaThread thread) {
final long BAD_TID = -1L;
Oop threadObj = thread.getThreadObj();
Klass klass = threadObj.getKlass();
if (!(klass instanceof InstanceKlass)) return BAD_TID;
InstanceKlass instanceKlass = (InstanceKlass) klass;
Field tidField = instanceKlass.findField("tid", TypeCode.LONG);
if (!(tidField instanceof LongField)) return BAD_TID;
long tid = ((LongField) tidField).getValue(threadObj);
return tid;
}
}
@Data(staticConstructor="of")
public static class ThreadInfo {
private Address address;
private long tid;
private long nid;
public ThreadInfo(final Address address, final long tid, final long nid) {
this.address = address;
this.tid = tid;
this.nid = nid;
}
public Address getAddress() {
return address;
}
public void setAddress(final Address address) {
this.address = address;
}
public long getTid() {
return tid;
}
public void setTid(final long tid) {
this.tid = tid;
}
public long getNid() {
return nid;
}
public void setNid(final long nid) {
this.nid = nid;
}
}
public interface TypeCode {
String BOOLEAN = "Z";
String BYTE = "B";
String CHAR = "C";
String SHORT = "S";
String INT = "I";
String LONG = "J";
String FLOAT = "F";
String DOUBLE = "D";
}
}
sudo java -classpath "/usr/lib/jvm/java-7-openjdk-amd64/lib/sa-jdi.jar:lombok.jar:." PrintThreadIds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment