Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active August 29, 2015 14:11
Show Gist options
  • Save thomasdarimont/dbb6796505eeaa692c91 to your computer and use it in GitHub Desktop.
Save thomasdarimont/dbb6796505eeaa692c91 to your computer and use it in GitHub Desktop.
Determine # of instances of a Java Klass in Java 9 via js with Nashorn, HotspotAgent

We use Java 9 since it's new and already includes sa-jdi.jar in classpath :) Note that the debugee JVM dosen't need to be Java 9.

tom@gauss ~/dev/repos/thomasdarimont/playground/tmp $ java -version
java version "1.9.0-ea"
Java(TM) SE Runtime Environment (build 1.9.0-ea-b41)
Java HotSpot(TM) 64-Bit Server VM (build 1.9.0-ea-b41, mixed mode)

Debugee JVM

We'll attach to this JVM so we need it's PID

$ jrunscript

Java.type("java.lang.management.ManagementFactory").getRuntimeMXBean().getName().split("@")[0]
> 42359

Debugger JVM

We connect to the debuggee JVM via the HotSpotAgent

$ sudo jrunscript

var HotSpotAgent = Java.type("sun.jvm.hotspot.HotSpotAgent")
var agent = new HotSpotAgent()
agent.attach(42359)

var SystemDictionaryHelper = Java.type("sun.jvm.hotspot.utilities.SystemDictionaryHelper")
var FindObjectByType = Java.type("sun.jvm.hotspot.utilities.FindObjectByType")

var VM = Java.type("sun.jvm.hotspot.runtime.VM")
var heapVisitor = new FindObjectByType(SystemDictionaryHelper.findInstanceKlass("java.lang.String"))

VM.getVM().getObjectHeap().iterate(heapVisitor);
heapVisitor.getResults().length
>24375
@thomasdarimont
Copy link
Author

More cool stuff with Nashorn and sa-jdi's HotspotAgent: https://gist.github.com/thomasdarimont/dc6ac8e48de17c124480

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment