Skip to content

Instantly share code, notes, and snippets.

@liaoyw
Forked from t3rmin4t0r/MonBuffers.java
Created August 10, 2018 07:38
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 liaoyw/5833cb783c2728204bd39b39e007e29b to your computer and use it in GitHub Desktop.
Save liaoyw/5833cb783c2728204bd39b39e007e29b 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