Search in sources :

Example 96 with MemoryPoolMXBean

use of java.lang.management.MemoryPoolMXBean in project qpid-broker-j by apache.

the class BrokerAttributeInjector method getInjectedStatistics.

@Override
public Collection<ConfiguredObjectInjectedStatistic<?, ?>> getInjectedStatistics() {
    List<ConfiguredObjectInjectedStatistic<?, ?>> statistics = new ArrayList<>();
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        String poolName = memoryPoolMXBean.getName().replace(" ", "");
        String statisticName = "jvmMemoryUsed" + poolName;
        try {
            Method getMemoryPoolUsed = BrokerAttributeInjector.class.getDeclaredMethod("getMemoryPoolUsed", Broker.class, MemoryPoolMXBean.class);
            final ConfiguredObjectInjectedStatistic<?, ?> injectedStatistic = new ConfiguredObjectInjectedStatistic<>(statisticName, getMemoryPoolUsed, new Object[] { memoryPoolMXBean }, "Usage of memory in pool " + memoryPoolMXBean.getName(), _typeValidator, StatisticUnit.BYTES, StatisticType.POINT_IN_TIME, memoryPoolMXBean.getName() + " Memory Used", null, true);
            statistics.add(injectedStatistic);
        } catch (NoSuchMethodException e) {
            LOGGER.warn("Failed to inject statistic '{}'", statisticName, e);
        }
    }
    for (GarbageCollectorMXBean garbageCollectorMXBean : ManagementFactory.getGarbageCollectorMXBeans()) {
        String gcName = garbageCollectorMXBean.getName().replace(" ", "");
        String jvmGCCollectionTimeStatisticName = "jvmGCCollectionTime" + gcName;
        try {
            Method getGCCollectionTime = BrokerAttributeInjector.class.getDeclaredMethod("getGCCollectionTime", Broker.class, GarbageCollectorMXBean.class);
            final ConfiguredObjectInjectedStatistic<?, ?> injectedStatistic = new ConfiguredObjectInjectedStatistic<>(jvmGCCollectionTimeStatisticName, getGCCollectionTime, new Object[] { garbageCollectorMXBean }, "Cumulative time in ms taken to perform collections for GC " + garbageCollectorMXBean.getName(), _typeValidator, StatisticUnit.COUNT, StatisticType.CUMULATIVE, garbageCollectorMXBean.getName() + " GC Collection Time", null, true);
            statistics.add(injectedStatistic);
        } catch (NoSuchMethodException e) {
            LOGGER.warn("Failed to inject statistic '{}'", jvmGCCollectionTimeStatisticName, e);
        }
        String jvmGCCollectionCountStatisticName = "jvmGCCollectionCount" + gcName;
        try {
            Method getGCCollectionCount = BrokerAttributeInjector.class.getDeclaredMethod("getGCCollectionCount", Broker.class, GarbageCollectorMXBean.class);
            final ConfiguredObjectInjectedStatistic<?, ?> injectedStatistic = new ConfiguredObjectInjectedStatistic<>(jvmGCCollectionCountStatisticName, getGCCollectionCount, new Object[] { garbageCollectorMXBean }, "Cumulative number of collections for GC " + garbageCollectorMXBean.getName(), _typeValidator, StatisticUnit.COUNT, StatisticType.CUMULATIVE, garbageCollectorMXBean.getName() + " GC Collection Count", null, true);
            statistics.add(injectedStatistic);
        } catch (NoSuchMethodException e) {
            LOGGER.warn("Failed to inject statistic '{}'", jvmGCCollectionCountStatisticName, e);
        }
    }
    if (_operatingSystemMXBean != null) {
        try {
            Method method = _operatingSystemMXBeanClass.getDeclaredMethod("getProcessCpuTime");
            ToLongFunction<Broker> supplier = broker -> {
                try {
                    final Object returnValue = method.invoke(_operatingSystemMXBean);
                    if (returnValue instanceof Number) {
                        return ((Number) returnValue).longValue();
                    }
                } catch (IllegalAccessException | InvocationTargetException e) {
                    LOGGER.warn("Unable to get cumulative process CPU time");
                }
                return -1L;
            };
            Method getLongValue = BrokerAttributeInjector.class.getDeclaredMethod("getLongValue", Broker.class, ToLongFunction.class);
            final ConfiguredObjectInjectedStatistic<?, ?> injectedStatistic = new ConfiguredObjectInjectedStatistic<>("processCpuTime", getLongValue, new Object[] { supplier }, "Cumulative process CPU time", _typeValidator, StatisticUnit.TIME_DURATION, StatisticType.CUMULATIVE, _operatingSystemMXBeanClass.getName() + " Process CPU Time", "process_cpu_time_nanoseconds", true);
            statistics.add(injectedStatistic);
        } catch (NoSuchMethodException | SecurityException e) {
            LOGGER.warn("Failed to inject statistic 'getProcessCpuTime'");
            LOGGER.debug("Exception:", e);
        }
        try {
            Method method = _operatingSystemMXBeanClass.getDeclaredMethod("getProcessCpuLoad");
            method.setAccessible(true);
            Function<Broker, BigDecimal> supplier = broker -> {
                try {
                    final Object returnValue = method.invoke(_operatingSystemMXBean);
                    if (returnValue instanceof Number) {
                        return BigDecimal.valueOf(((Number) returnValue).doubleValue()).setScale(4, RoundingMode.HALF_UP);
                    }
                } catch (IllegalAccessException | InvocationTargetException e) {
                    LOGGER.warn("Unable to get current process CPU load", e);
                }
                return BigDecimal.valueOf(-1L);
            };
            Method getBigDecimalValue = BrokerAttributeInjector.class.getDeclaredMethod("getBigDecimalValue", Broker.class, Function.class);
            final ConfiguredObjectInjectedStatistic<?, ?> injectedStatistic = new ConfiguredObjectInjectedStatistic<>("processCpuLoad", getBigDecimalValue, new Object[] { supplier }, "Current process CPU load", _typeValidator, StatisticUnit.COUNT, StatisticType.POINT_IN_TIME, _operatingSystemMXBean.getName() + " Process CPU Load", null, true);
            statistics.add(injectedStatistic);
        } catch (NoSuchMethodException e) {
            LOGGER.warn("Failed to inject statistic 'getProcessCpuLoad'");
            LOGGER.debug("Exception:", e);
        }
    }
    return statistics;
}
Also used : Logger(org.slf4j.Logger) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) BrokerMessages(org.apache.qpid.server.logging.messages.BrokerMessages) Function(java.util.function.Function) ConfiguredObjectAttributeInjector(org.apache.qpid.server.plugin.ConfiguredObjectAttributeInjector) ParameterizedTypes(org.apache.qpid.server.util.ParameterizedTypes) InvocationTargetException(java.lang.reflect.InvocationTargetException) ArrayList(java.util.ArrayList) BigDecimal(java.math.BigDecimal) List(java.util.List) GarbageCollectorMXBean(java.lang.management.GarbageCollectorMXBean) MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean) PluggableService(org.apache.qpid.server.plugin.PluggableService) Map(java.util.Map) PlatformManagedObject(java.lang.management.PlatformManagedObject) ManagementFactory(java.lang.management.ManagementFactory) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean) ToLongFunction(java.util.function.ToLongFunction) Method(java.lang.reflect.Method) RoundingMode(java.math.RoundingMode) ArrayList(java.util.ArrayList) GarbageCollectorMXBean(java.lang.management.GarbageCollectorMXBean) Method(java.lang.reflect.Method) BigDecimal(java.math.BigDecimal) PlatformManagedObject(java.lang.management.PlatformManagedObject) MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean)

Example 97 with MemoryPoolMXBean

use of java.lang.management.MemoryPoolMXBean in project ballerina by ballerina-lang.

the class ObjectSizeCalculator method getEffectiveMemoryLayoutSpecification.

@VisibleForTesting
static MemoryLayoutSpecification getEffectiveMemoryLayoutSpecification() {
    final String vmName = System.getProperty("java.vm.name");
    if (vmName == null || !(vmName.startsWith("Java HotSpot(TM) ") || vmName.startsWith("OpenJDK") || vmName.startsWith("TwitterJDK"))) {
        throw new UnsupportedOperationException("ObjectSizeCalculator only supported on HotSpot VM");
    }
    final String dataModel = System.getProperty("sun.arch.data.model");
    if ("32".equals(dataModel)) {
        // Running with 32-bit data model.
        return new MemoryLayoutSpecification() {

            @Override
            public int getArrayHeaderSize() {
                return 12;
            }

            @Override
            public int getObjectHeaderSize() {
                return 8;
            }

            @Override
            public int getObjectPadding() {
                return 8;
            }

            @Override
            public int getReferenceSize() {
                return 4;
            }

            @Override
            public int getSuperclassFieldPadding() {
                return 4;
            }
        };
    } else if (!"64".equals(dataModel)) {
        throw new UnsupportedOperationException("Unrecognized value '" + dataModel + "' of sun.arch.data.model system property");
    }
    final String strVmVersion = System.getProperty("java.vm.version");
    final int vmVersion = Integer.parseInt(strVmVersion.substring(0, strVmVersion.indexOf('.')));
    if (vmVersion >= 17) {
        long maxMemory = 0;
        for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
            maxMemory += mp.getUsage().getMax();
        }
        if (maxMemory < 30L * 1024 * 1024 * 1024) {
            // for all memory pools (yes, including code cache).
            return new MemoryLayoutSpecification() {

                @Override
                public int getArrayHeaderSize() {
                    return 16;
                }

                @Override
                public int getObjectHeaderSize() {
                    return 12;
                }

                @Override
                public int getObjectPadding() {
                    return 8;
                }

                @Override
                public int getReferenceSize() {
                    return 4;
                }

                @Override
                public int getSuperclassFieldPadding() {
                    return 4;
                }
            };
        }
    }
    // In other cases, it's a 64-bit uncompressed OOPs object model
    return new MemoryLayoutSpecification() {

        @Override
        public int getArrayHeaderSize() {
            return 24;
        }

        @Override
        public int getObjectHeaderSize() {
            return 16;
        }

        @Override
        public int getObjectPadding() {
            return 8;
        }

        @Override
        public int getReferenceSize() {
            return 8;
        }

        @Override
        public int getSuperclassFieldPadding() {
            return 8;
        }
    };
}
Also used : MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 98 with MemoryPoolMXBean

use of java.lang.management.MemoryPoolMXBean in project cassandra by apache.

the class CassandraDaemon method logSystemInfo.

private void logSystemInfo() {
    if (logger.isInfoEnabled()) {
        try {
            logger.info("Hostname: {}", InetAddress.getLocalHost().getHostName() + ":" + DatabaseDescriptor.getStoragePort() + ":" + DatabaseDescriptor.getSSLStoragePort());
        } catch (UnknownHostException e1) {
            logger.info("Could not resolve local host");
        }
        logger.info("JVM vendor/version: {}/{}", JAVA_VM_NAME.getString(), JAVA_VERSION.getString());
        logger.info("Heap size: {}/{}", FBUtilities.prettyPrintMemory(Runtime.getRuntime().totalMemory()), FBUtilities.prettyPrintMemory(Runtime.getRuntime().maxMemory()));
        for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) logger.info("{} {}: {}", pool.getName(), pool.getType(), pool.getPeakUsage());
        logger.info("Classpath: {}", JAVA_CLASS_PATH.getString());
        logger.info("JVM Arguments: {}", ManagementFactory.getRuntimeMXBean().getInputArguments());
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean)

Example 99 with MemoryPoolMXBean

use of java.lang.management.MemoryPoolMXBean in project pinpoint by naver.

the class DefaultDetailedMemoryMetricTest method testNullMemoryUsage.

@Test
public void testNullMemoryUsage() {
    // Given
    MemoryPoolMXBean mockMXBean = mock(MemoryPoolMXBean.class);
    MemoryUsage nullMemoryUsage = null;
    when(mockMXBean.getUsage()).thenReturn(nullMemoryUsage);
    DetailedMemoryMetric detailedMemoryMetric = new DefaultDetailedMemoryMetric(MemoryPoolType.CMS, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean);
    // When
    DetailedMemoryMetricSnapshot snapshot = detailedMemoryMetric.getSnapshot();
    // Then
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getNewGenUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getOldGenUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getSurvivorSpaceUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getCodeCacheUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getPermGenUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getMetaspaceUsage(), 0.0);
}
Also used : MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean) MemoryUsage(java.lang.management.MemoryUsage) Test(org.junit.Test)

Example 100 with MemoryPoolMXBean

use of java.lang.management.MemoryPoolMXBean in project pinpoint by naver.

the class DefaultDetailedMemoryMetricTest method testUnknownMax.

@Test
public void testUnknownMax() {
    // Given
    MemoryPoolMXBean mockMXBean = mock(MemoryPoolMXBean.class);
    MemoryUsage mockUsage = mock(MemoryUsage.class);
    when(mockMXBean.getUsage()).thenReturn(mockUsage);
    when(mockUsage.getMax()).thenReturn(-1L);
    DetailedMemoryMetric detailedMemoryMetric = new DefaultDetailedMemoryMetric(MemoryPoolType.CMS, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean, mockMXBean);
    // When
    DetailedMemoryMetricSnapshot snapshot = detailedMemoryMetric.getSnapshot();
    // Then
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getNewGenUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getOldGenUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getSurvivorSpaceUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getCodeCacheUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getPermGenUsage(), 0.0);
    Assert.assertEquals(DetailedMemoryMetric.UNCOLLECTED_USAGE, snapshot.getMetaspaceUsage(), 0.0);
}
Also used : MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean) MemoryUsage(java.lang.management.MemoryUsage) Test(org.junit.Test)

Aggregations

MemoryPoolMXBean (java.lang.management.MemoryPoolMXBean)112 MemoryUsage (java.lang.management.MemoryUsage)46 GarbageCollectorMXBean (java.lang.management.GarbageCollectorMXBean)16 ArrayList (java.util.ArrayList)15 MemoryMXBean (java.lang.management.MemoryMXBean)12 Test (org.testng.annotations.Test)11 InstanceNotFoundException (javax.management.InstanceNotFoundException)9 ReflectionException (javax.management.ReflectionException)9 NotificationEmitter (javax.management.NotificationEmitter)8 MemoryType (java.lang.management.MemoryType)7 HashMap (java.util.HashMap)7 Map (java.util.Map)7 AttributeNotFoundException (javax.management.AttributeNotFoundException)7 IntrospectionException (javax.management.IntrospectionException)7 MBeanException (javax.management.MBeanException)7 VisibleForTesting (com.google.common.annotations.VisibleForTesting)6 Attribute (javax.management.Attribute)6 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)6 BufferPoolMXBean (java.lang.management.BufferPoolMXBean)5 ThreadMXBean (java.lang.management.ThreadMXBean)5