Skip to content

Instantly share code, notes, and snippets.

@t3rmin4t0r
Created January 15, 2016 06:59
Show Gist options
  • Save t3rmin4t0r/1a753ccdcfa8d111f07c to your computer and use it in GitHub Desktop.
Save t3rmin4t0r/1a753ccdcfa8d111f07c to your computer and use it in GitHub Desktop.
Monitoring direct memory in the JVM (from https://blogs.oracle.com/alanb/entry/monitoring_direct_buffers, adapted for JDK8)
import java.io.File;
import java.util.*;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.*;
import com.sun.tools.attach.VirtualMachine; // Attach API
/**
* Simple tool to attach to running VM to report buffer pool usage.
*/
public class MonBuffers {
static final String CONNECTOR_ADDRESS =
"com.sun.management.jmxremote.localConnectorAddress";
public static void main(String args[]) throws Exception {
// attach to target VM to get connector address
VirtualMachine vm = VirtualMachine.attach(args[0]);
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
// start management agent
String agent = vm.getSystemProperties().getProperty("java.home") +
File.separator + "lib" + File.separator + "management-agent.jar";
vm.loadAgent(agent);
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
assert connectorAddress != null;
}
// connect to agent
JMXServiceURL url = new JMXServiceURL(connectorAddress);
JMXConnector c = JMXConnectorFactory.connect(url);
MBeanServerConnection server = c.getMBeanServerConnection();
// get the list of pools
Set<ObjectName> mbeans = server.queryNames(
new ObjectName("java.nio:type=BufferPool,*"), null);
List<BufferPoolMXBean> pools = new ArrayList<BufferPoolMXBean>();
for (ObjectName name: mbeans) {
BufferPoolMXBean pool = ManagementFactory
.newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class);
pools.add(pool);
}
// print headers
for (BufferPoolMXBean pool: pools)
System.out.format(" %8s ", pool.getName());
System.out.println();
for (int i=0; i<pools.size(); i++)
System.out.format("%6s %10s %10s ", "Count", "Capacity", "Memory");
System.out.println();
// poll and print usage
for (;;) {
for (BufferPoolMXBean pool: pools) {
System.out.format("%6d %10d %10d ",
pool.getCount(), pool.getTotalCapacity(), pool.getMemoryUsed());
}
System.out.println();
Thread.sleep(2000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment