Skip to content

Instantly share code, notes, and snippets.

@charleehu
Forked from rednaxelafx/DirectMemorySize.java
Created January 30, 2012 09:05
Show Gist options
  • Save charleehu/1703466 to your computer and use it in GitHub Desktop.
Save charleehu/1703466 to your computer and use it in GitHub Desktop.
An Serviceability-Agent based tool to see stats of NIO direct memory, as an alternative on JDKs without JMX support for direct memory monitoring.
$ java -version
java version "1.6.0_30"
Java(TM) SE Runtime Environment (build 1.6.0_30-b12)
Java HotSpot(TM) 64-Bit Server VM (build 20.5-b03, mixed mode)
$ javac -classpath $JAVA_HOME/lib/sa-jdi.jar DirectMemorySize.java
$ jps
18486 GroovyStarter
23135 Jps
$ java -classpath .:$JAVA_HOME/lib/sa-jdi.jar DirectMemorySize `pgrep java`
Attaching to process ID 18486, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.5-b03
NIO direct memory: (in bytes)
reserved size = 0.000000 MB (0 bytes)
max size = 4069.000000 MB (4266655744 bytes)
import java.io.*;
import java.util.*;
import sun.jvm.hotspot.memory.*;
import sun.jvm.hotspot.oops.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.runtime.*;
import sun.jvm.hotspot.tools.*;
import sun.jvm.hotspot.utilities.*;
public class DirectMemorySize extends Tool {
public void run() {
// Ready to go with the database...
try {
long reservedMemory = getStaticLongFieldValue("java.nio.Bits", "reservedMemory");
long directMemory = getStaticLongFieldValue("sun.misc.VM", "directMemory");
System.out.println("NIO direct memory:");
System.out.printf(" reserved size = %fMB (%d bytes)\n", toM(reservedMemory), reservedMemory);
System.out.printf(" max size = %fMB (%d bytes)\n", toM(directMemory), directMemory);
} catch (AddressException e) {
System.err.println("Error accessing address 0x"
+ Long.toHexString(e.getAddress()));
e.printStackTrace();
}
}
public static long getStaticLongFieldValue(String className, String fieldName) {
InstanceKlass klass = SystemDictionaryHelper.findInstanceKlass(className);
LongField field = (LongField) klass.findField(fieldName, "J");
return field.getValue(klass);
}
public static double toM(long value) {
return value / (1024 * 1024.0);
}
public String getName() {
return "directMemorySize";
}
public static void main(String[] args) {
DirectMemorySize tool = new DirectMemorySize();
tool.start(args);
tool.stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment