Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Forked from jvican/RuntimeUtils.scala
Created October 14, 2019 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/e4b4f83f53532531164277f56e817e5c to your computer and use it in GitHub Desktop.
Save xuwei-k/e4b4f83f53532531164277f56e817e5c 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