public static void main(String[] args) throws IOException { JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi"); JMXConnector connector = JMXConnectorFactory.connect(address); MBeanServerConnection msc = connector.getMBeanServerConnection(); HotSpotDiagnosticMXBean hotspot = ManagementFactory.newPlatformMXBeanProxy( msc, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class); hotspot.dumpHeap("out.txt", true); }
public static <T> T getRemoteBean( Class<T> clazz, String mbeanName, IConfiguration config, boolean mxbean) { try { if (mxbean) return ManagementFactory.newPlatformMXBeanProxy( JMXNodeTool.instance(config).mbeanServerConn, mbeanName, clazz); else return JMX.newMBeanProxy( JMXNodeTool.instance(config).mbeanServerConn, new ObjectName(mbeanName), clazz); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; }
public static JSONObject geGCInfo(String app) throws Exception { ObjectName obj = new ObjectName("java.lang:type=GarbageCollector,*"); MBeanServer conn = ManagementFactory.getPlatformMBeanServer(); Set<ObjectInstance> MBeanset = conn.queryMBeans(obj, null); Class<GarbageCollectorMXBean> cls = GarbageCollectorMXBean.class; JSONObject data = new JSONObject(); for (ObjectInstance objx : MBeanset) { String name = objx.getObjectName().getCanonicalName(); String keyName = objx.getObjectName().getKeyProperty("name"); GarbageCollectorMXBean gc = ManagementFactory.newPlatformMXBeanProxy(conn, name, cls); data.put(keyName + "-time", gc.getCollectionTime() / 1000.0); data.put(keyName + "-count", gc.getCollectionCount()); } return data; }
static void MonitorGC(long h) { handle = h; List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans(); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { ObjectName gcName = new ObjectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*"); for (ObjectName name : server.queryNames(gcName, null)) { GarbageCollectorMXBean gc = ManagementFactory.newPlatformMXBeanProxy( server, name.getCanonicalName(), GarbageCollectorMXBean.class); gcbeans.add(gc); NotificationEmitter emitter = (NotificationEmitter) gc; NotificationListener listener = new NotificationListener() { @Override public void handleNotification(Notification notification, Object handback) { if (notification .getType() .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) { CompositeData ndata = (CompositeData) notification.getUserData(); GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(ndata); boolean major = "end of major GC".equals(info.getGcAction()); long free = Runtime.getRuntime().freeMemory(); long total = Runtime.getRuntime().totalMemory(); long qty = (15 * total) - (free * 100); if (qty > 0) { NotifyOSv(handle, qty); } } } }; emitter.addNotificationListener(listener, null, null); } } catch (Exception e) { throw new RuntimeException(e); } }
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub if (args.length != 4) { System.err.println("Please provide process id zabbix-host zabbix-port host-guid"); System.exit(-1); } String processPid = args[0]; String zabbixHost = args[1]; String zabbixPort = args[2]; String hostGuid = args[3]; VirtualMachine vm = VirtualMachine.attach(processPid); String connectorAddr = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress"); if (connectorAddr == null) { String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar"; vm.loadAgent(agent); connectorAddr = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress"); } JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr); JMXConnector connector = JMXConnectorFactory.connect(serviceURL); MBeanServerConnection mbsc = connector.getMBeanServerConnection(); ObjectName objName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); Set<ObjectName> mbeans = mbsc.queryNames(objName, null); for (ObjectName name : mbeans) { ThreadMXBean threadBean; threadBean = ManagementFactory.newPlatformMXBeanProxy(mbsc, name.toString(), ThreadMXBean.class); long threadIds[] = threadBean.getAllThreadIds(); for (long threadId : threadIds) { ThreadInfo threadInfo = threadBean.getThreadInfo(threadId); System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState()); } } }
/** * @param args the command line arguments: must be -url <jmx-url>, or -port <port-number> [-host * <host-or-ip], or -pid <pid>, or -help */ public static void main(String[] args) throws Exception { // Parse arguments. final ConnectionArgs cArgs = new ConnectionArgs(args); // Get target's URL final JMXServiceURL target = cArgs.getJMXServiceURL(); // Connect to target (assuming no security) final JMXConnector connector = JMXConnectorFactory.connect(target); // Get an MBeanServerConnection on the remote VM. final MBeanServerConnection remote = connector.getMBeanServerConnection(); final RuntimeMXBean remoteRuntime = ManagementFactory.newPlatformMXBeanProxy( remote, ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class); System.out.println("Target VM is: " + remoteRuntime.getName()); System.out.println("Started since: " + remoteRuntime.getUptime()); System.out.println("With Classpath: " + remoteRuntime.getClassPath()); System.out.println("And args: " + remoteRuntime.getInputArguments()); connector.close(); }
public GCInspector() { // we only want this class to do its thing on sun jdks, or when the sun classes are present. Class<?> gcBeanClass = null; try { gcBeanClass = Class.forName("com.sun.management.GarbageCollectorMXBean"); Class.forName("com.sun.management.GcInfo"); } catch (ClassNotFoundException ex) { // this happens when using a non-sun jdk. logger.warn("Cannot load sun GC monitoring classes. GCInspector is disabled."); } MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { ObjectName gcName = new ObjectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*"); for (ObjectName name : server.queryNames(gcName, null)) { Object gc = ManagementFactory.newPlatformMXBeanProxy(server, name.getCanonicalName(), gcBeanClass); beans.add(gc); } } catch (Exception e) { throw new RuntimeException(e); } }
/** Initialize constants and try to collect information about the JVM internals. */ static { // Initialize empirically measured defaults. We'll modify them to the current // JVM settings later on if possible. int referenceSize = Constants.JRE_IS_64BIT ? 8 : 4; int objectHeader = Constants.JRE_IS_64BIT ? 16 : 8; // The following is objectHeader + NUM_BYTES_INT, but aligned (object alignment) // so on 64 bit JVMs it'll be align(16 + 4, @8) = 24. int arrayHeader = Constants.JRE_IS_64BIT ? 24 : 12; supportedFeatures = EnumSet.noneOf(JvmFeature.class); Class<?> unsafeClass = null; Object tempTheUnsafe = null; try { unsafeClass = Class.forName("sun.misc.Unsafe"); final Field unsafeField = unsafeClass.getDeclaredField("theUnsafe"); unsafeField.setAccessible(true); tempTheUnsafe = unsafeField.get(null); } catch (Exception e) { // Ignore. } theUnsafe = tempTheUnsafe; // get object reference size by getting scale factor of Object[] arrays: try { final Method arrayIndexScaleM = unsafeClass.getMethod("arrayIndexScale", Class.class); referenceSize = ((Number) arrayIndexScaleM.invoke(theUnsafe, Object[].class)).intValue(); supportedFeatures.add(JvmFeature.OBJECT_REFERENCE_SIZE); } catch (Exception e) { // ignore. } // "best guess" based on reference size. We will attempt to modify // these to exact values if there is supported infrastructure. objectHeader = Constants.JRE_IS_64BIT ? (8 + referenceSize) : 8; arrayHeader = Constants.JRE_IS_64BIT ? (8 + 2 * referenceSize) : 12; // get the object header size: // - first try out if the field offsets are not scaled (see warning in Unsafe docs) // - get the object header size by getting the field offset of the first field of a dummy object // If the scaling is byte-wise and unsafe is available, enable dynamic size measurement for // estimateRamUsage(). Method tempObjectFieldOffsetMethod = null; try { final Method objectFieldOffsetM = unsafeClass.getMethod("objectFieldOffset", Field.class); final Field dummy1Field = DummyTwoLongObject.class.getDeclaredField("dummy1"); final int ofs1 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy1Field)).intValue(); final Field dummy2Field = DummyTwoLongObject.class.getDeclaredField("dummy2"); final int ofs2 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy2Field)).intValue(); if (Math.abs(ofs2 - ofs1) == NUM_BYTES_LONG) { final Field baseField = DummyOneFieldObject.class.getDeclaredField("base"); objectHeader = ((Number) objectFieldOffsetM.invoke(theUnsafe, baseField)).intValue(); supportedFeatures.add(JvmFeature.FIELD_OFFSETS); tempObjectFieldOffsetMethod = objectFieldOffsetM; } } catch (Exception e) { // Ignore. } objectFieldOffsetMethod = tempObjectFieldOffsetMethod; // Get the array header size by retrieving the array base offset // (offset of the first element of an array). try { final Method arrayBaseOffsetM = unsafeClass.getMethod("arrayBaseOffset", Class.class); // we calculate that only for byte[] arrays, it's actually the same for all types: arrayHeader = ((Number) arrayBaseOffsetM.invoke(theUnsafe, byte[].class)).intValue(); supportedFeatures.add(JvmFeature.ARRAY_HEADER_SIZE); } catch (Exception e) { // Ignore. } NUM_BYTES_OBJECT_REF = referenceSize; NUM_BYTES_OBJECT_HEADER = objectHeader; NUM_BYTES_ARRAY_HEADER = arrayHeader; // Try to get the object alignment (the default seems to be 8 on Hotspot, // regardless of the architecture). int objectAlignment = 8; try { final Class<?> beanClazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean"); // Try to get the diagnostic mxbean without calling {@link // ManagementFactory#getPlatformMBeanServer()} // which starts AWT thread (and shows junk in the dock) on a Mac: Object hotSpotBean; // Java 7+, HotSpot try { hotSpotBean = ManagementFactory.class .getMethod("getPlatformMXBean", Class.class) .invoke(null, beanClazz); } catch (Exception e1) { // Java 6, HotSpot try { Class<?> sunMF = Class.forName("sun.management.ManagementFactory"); hotSpotBean = sunMF.getMethod("getDiagnosticMXBean").invoke(null); } catch (Exception e2) { // Last resort option is an attempt to get it from ManagementFactory's server anyway (may // start AWT). hotSpotBean = ManagementFactory.newPlatformMXBeanProxy( ManagementFactory.getPlatformMBeanServer(), "com.sun.management:type=HotSpotDiagnostic", beanClazz); } } if (hotSpotBean != null) { final Method getVMOptionMethod = beanClazz.getMethod("getVMOption", String.class); final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "ObjectAlignmentInBytes"); objectAlignment = Integer.parseInt(vmOption.getClass().getMethod("getValue").invoke(vmOption).toString()); supportedFeatures.add(JvmFeature.OBJECT_ALIGNMENT); } } catch (Exception e) { // Ignore. } NUM_BYTES_OBJECT_ALIGNMENT = objectAlignment; JVM_INFO_STRING = "[JVM: " + Constants.JVM_NAME + ", " + Constants.JVM_VERSION + ", " + Constants.JVM_VENDOR + ", " + Constants.JAVA_VENDOR + ", " + Constants.JAVA_VERSION + "]"; }