Last active
November 22, 2019 16:14
-
-
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.
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
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