Skip to content

Instantly share code, notes, and snippets.

@jvican
Last active November 22, 2019 16:14
Show Gist options
  • Save jvican/e9b08fb423c464b011bc44e6337f8487 to your computer and use it in GitHub Desktop.
Save jvican/e9b08fb423c464b011bc44e6337f8487 to your computer and use it in GitHub Desktop.
Some Scala code that uses Java APIs present in tools.jar (only JDKs) to programmatically produce a jstack-like thread dump. Useful to debug application and test deadlocks.
object RuntimeUtils {
def requestThreadDump: String = {
// Get the PID of the current JVM process
val selfName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
val selfPid = selfName.substring(0, selfName.indexOf('@'))
// Attach to the VM
import com.sun.tools.attach.VirtualMachine
import sun.tools.attach.HotSpotVirtualMachine;
val vm = VirtualMachine.attach(selfPid);
val hotSpotVm = vm.asInstanceOf[HotSpotVirtualMachine];
// Request a thread dump
val inputStream = hotSpotVm.remoteDataDump()
try new String(Stream.continually(inputStream.read).takeWhile(_ != -1).map(_.toByte).toArray)
finally inputStream.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment