java.lang.management.MemoryMXBean Java Examples

The following examples show how to use java.lang.management.MemoryMXBean. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SysUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
	 * 内存信息
	 * 
	 * @author JiangZhiYong
	 * @QQ 359135103 2017年10月12日 下午3:39:22
	 * @param spliteStr
	 * @return
	 */
	public static String memoryInfo(String spliteStr) {
		MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
		StringBuilder sb = new StringBuilder();
		sb.append("堆内存使用:   ").append(bean.getHeapMemoryUsage()).append(spliteStr);
		sb.append("栈内存使用:   ").append(bean.getNonHeapMemoryUsage()).append(spliteStr);
		sb.append("挂起对象数:   ").append(bean.getObjectPendingFinalizationCount()).append(spliteStr);
		//内存池
		List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans();
		for(int i=0;i<beans.size();i++) {
			MemoryPoolMXBean b=beans.get(i);
//			sb.append(i).append("垃圾回收后内存:   ").append(b.getCollectionUsage()).append(spliteStr);
//			sb.append(i).append("内存池的回收使用量阈值:   ").append(b.getCollectionUsageThreshold()).append(spliteStr);
//			sb.append(i).append("虚拟机已检测到内存使用量达到或超过回收使用量阈值的次数:   ").append(b.getCollectionUsageThresholdCount()).append(spliteStr);
			sb.append(i).append("内存池管理器名称:   ").append(b.getMemoryManagerNames().toString()).append(spliteStr);
			sb.append(i).append("内存池名称:   ").append(b.getName()).append(spliteStr);
			sb.append(i).append("内存使用峰值:   ").append(b.getPeakUsage()).append(spliteStr);
			sb.append(i).append("内存池类型:   ").append(b.getType()).append(spliteStr);
			sb.append(i).append("内存池使用量:   ").append(b.getUsage()).append(spliteStr);
//			sb.append(i).append("内存使用量阀值:   ").append(b.getUsageThreshold()).append(spliteStr);
//			sb.append(i).append("超过阀值次数:   ").append(b.getUsageThresholdCount()).append(spliteStr);
		}
		return sb.toString();
	}
 
Example #2
Source File: Main.java    From pravega with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static void onShutdown(ControllerServiceMain controllerServiceMain) {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    memoryMXBean.setVerbose(true);
    log.info("Shutdown hook memory usage dump: Heap memory usage: {}, non heap memory usage {}", memoryMXBean.getHeapMemoryUsage(),
            memoryMXBean.getNonHeapMemoryUsage());

    log.info("Controller service shutting down");
    try {
        controllerServiceMain.stopAsync();
        controllerServiceMain.awaitTerminated();
    } finally {
        if (Config.DUMP_STACK_ON_SHUTDOWN) {
            Thread.getAllStackTraces().forEach((key, value) ->
                    log.info("Shutdown Hook Thread dump: Thread {} stackTrace: {} ", key.getName(), value));
        }
    }
}
 
Example #3
Source File: MemoryMeter.java    From DeconvolutionLab2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setDetail() {
	MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
	MemoryUsage heapU = mem.getHeapMemoryUsage();
	MemoryUsage nonhU = mem.getNonHeapMemoryUsage();
	Runtime runt = Runtime.getRuntime();
	int i = 0;
	add(i++, new String[] { "JVM", "Initial Memory (-Xms)", NumFormat.bytes(runt.freeMemory()) });
	add(i++, new String[] { "JVM", "Maximum Memory (-Xmx)", NumFormat.bytes(runt.maxMemory()) });
	add(i++, new String[] { "JVM", "Total Used Memory", NumFormat.bytes(runt.totalMemory()) });
	
	add(i++, new String[] { "Memory", "Heap Used", NumFormat.bytes(heapU.getUsed()) });
	add(i++, new String[] { "Memory", "Heap Init", NumFormat.bytes(heapU.getInit()) });
	add(i++, new String[] { "Memory", "Heap Max ", NumFormat.bytes(heapU.getMax()) });

	add(i++, new String[] { "Memory", "NonHeap Used", NumFormat.bytes(nonhU.getUsed()) });
	add(i++, new String[] { "Memory", "NonHeap Init", NumFormat.bytes(nonhU.getInit()) });
}
 
Example #4
Source File: JvmCheck.java    From appstatus with Apache License 2.0 6 votes vote down vote up
@Override
public ICheckResult checkStatus(Locale locale) {
	MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
	MemoryUsage heap = memory.getHeapMemoryUsage();
	long heapRatio = heap.getUsed() * 100 / heap.getMax();
	CheckResultBuilder result = result(this).messageBundle("net.sf.appstatus.core.check.impl.JvmCheck_msg", locale);
	if (heapRatio > limitError) {
		result.code(ICheckResult.ERROR).fatal().resolutionSteps("resolutionSteps.fatal", new Object[] {});
	} else if (heapRatio > limitWarn) {
		result.code(ICheckResult.ERROR).resolutionSteps("resolutionSteps.warn", new Object[] {});
	} else {
		result.code(ICheckResult.OK);
	}
	result.description("description", new Object[] { heapRatio });
	return result.build();
}
 
Example #5
Source File: IdleServerTasks.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Called when the server becomes idle. Should not block, but may invoke
 * new threads.
 */
public void idle() {
  Preconditions.checkState(!executor.isShutdown());

  @SuppressWarnings("unused")
  Future<?> possiblyIgnoredError =
      executor.schedule(
          () -> {
            MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
            MemoryUsage before = memBean.getHeapMemoryUsage();
            try (AutoProfiler p = GoogleAutoProfilerUtils.logged("Idle GC")) {
              System.gc();
            }
            MemoryUsage after = memBean.getHeapMemoryUsage();
            logger.atInfo().log(
                "[Idle GC] used: %s -> %s, committed: %s -> %s",
                StringUtilities.prettyPrintBytes(before.getUsed()),
                StringUtilities.prettyPrintBytes(after.getUsed()),
                StringUtilities.prettyPrintBytes(before.getCommitted()),
                StringUtilities.prettyPrintBytes(after.getCommitted()));
          },
          10,
          TimeUnit.SECONDS);
}
 
Example #6
Source File: GarbageCollectorMonitor.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
/**
 *  JVM memory snapshot
 **/
@Override
public MemoryStat memSnapshot() {
    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean() ;
    MemoryUsage heap = memBean.getHeapMemoryUsage();
    MemoryUsage nonHeap = memBean.getNonHeapMemoryUsage();
    MemoryStat stat=new MemoryStat();
    // heap
    stat.setHeapMax(heap.getMax());
    stat.setHeapInit(heap.getInit());
    stat.setHeapCommitted(heap.getCommitted());
    stat.setHeapUsed(heap.getUsed());
    // non-heap
    stat.setNonHeapInit(nonHeap.getInit());
    stat.setNonHeapMax(nonHeap.getMax());
    stat.setNonHeapUsed(nonHeap.getUsed());
    stat.setNonHeapCommitted(nonHeap.getCommitted());

    // allocated by ByteBuffer.allocateDirect()
    stat.setDirectBufferSize(SharedSecrets.getJavaNioAccess().getDirectBufferPool().getMemoryUsed());

    return stat;
}
 
Example #7
Source File: Test.java    From ClusterDeviceControlPlatform with MIT License 6 votes vote down vote up
private static void printMemoryInfo() {
    MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
    MemoryUsage headMemory = memory.getHeapMemoryUsage();
    System.out.println("head堆:");
    System.out.println("\t初始(M):" + headMemory.getInit() / MB);
    System.out.println("\t最大(上限)(M):" + headMemory.getMax() / MB);
    System.out.println("\t当前(已使用)(M):" + headMemory.getUsed() / MB);
    System.out.println("\t提交的内存(已申请)(M):" + headMemory.getCommitted() / MB);
    System.out.println("\t使用率:" + headMemory.getUsed() * 100 / headMemory.getCommitted() + "%");

    System.out.println("non-head非堆:");
    MemoryUsage nonheadMemory = memory.getNonHeapMemoryUsage();
    System.out.println("\t初始(M):" + nonheadMemory.getInit() / MB);
    System.out.println("\t最大(上限)(M):" + nonheadMemory.getMax() / MB);
    System.out.println("\t当前(已使用)(M):" + nonheadMemory.getUsed() / MB);
    System.out.println("\t提交的内存(已申请)(M):" + nonheadMemory.getCommitted() / MB);
    System.out.println("\t使用率:" + nonheadMemory.getUsed() * 100 / nonheadMemory.getCommitted() + "%");
}
 
Example #8
Source File: InfoUtil.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
public static List<Info> getGeneralJVMInfo() {
	List<Info> infos = new ArrayList<Info>();
	
	RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
	infos.add(new Info("uptime", "" + Duration.milliseconds(runtimeBean.getUptime()).toString()));
	infos.add(new Info("name", runtimeBean.getName()));
	infos.add(new Info("pid", runtimeBean.getName().split("@")[0]));
	
	OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean();
	infos.add(new Info("os name", "" + systemBean.getName()));
	infos.add(new Info("os version", "" + systemBean.getVersion()));
	infos.add(new Info("system load average", "" + systemBean.getSystemLoadAverage()));
	infos.add(new Info("available processors", "" + systemBean.getAvailableProcessors()));

	ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
	infos.add(new Info("thread count",  "" + threadBean.getThreadCount()));
	infos.add(new Info("peak thread count",  "" + threadBean.getPeakThreadCount()));
	
	MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
	infos.add(new Info("heap memory used",  FileUtils.byteCountToDisplaySize(memoryBean.getHeapMemoryUsage().getUsed())));
	infos.add(new Info("non-heap memory used",  FileUtils.byteCountToDisplaySize(memoryBean.getNonHeapMemoryUsage().getUsed())));
	
	return infos;
}
 
Example #9
Source File: MemoryView.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
MemoryView(Application application, AbstractSamplerSupport.Refresher refresher,
           MemoryMXBean memoryBean, MemorySamplerSupport.SnapshotDumper snapshotDumper,
           MemorySamplerSupport.HeapDumper heapDumper) {

    this.refresher = refresher;

    this.memoryBean = memoryBean;
    this.snapshotDumper = snapshotDumper;
    this.heapDumper = heapDumper;
    
    initComponents(application);

    addHierarchyListener(new HierarchyListener() {
        public void hierarchyChanged(HierarchyEvent e) {
            if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
                if (isShowing()) MemoryView.this.refresher.refresh();
            }
        }
    });
}
 
Example #10
Source File: MemoryWatchdog.java    From pitest with Apache License 2.0 6 votes vote down vote up
public static void addWatchDogToAllPools(final long threshold,
    final NotificationListener listener) {
  final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  final NotificationEmitter ne = (NotificationEmitter) memBean;

  ne.addNotificationListener(listener, null, null);

  final List<MemoryPoolMXBean> memPools = ManagementFactory
      .getMemoryPoolMXBeans();
  for (final MemoryPoolMXBean mp : memPools) {
    if (mp.isUsageThresholdSupported()) {
      final MemoryUsage mu = mp.getUsage();
      final long max = mu.getMax();
      final long alert = (max * threshold) / 100;
      // LOG.info("Setting a threshold shutdown on pool: " + mp.getName()
      // + " for: " + alert);
      mp.setUsageThreshold(alert);

    }
  }
}
 
Example #11
Source File: ThreadsMemoryView.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
ThreadsMemoryView(AbstractSamplerSupport.Refresher refresher, MemoryMXBean memoryBean, MemorySamplerSupport.HeapDumper heapDumper) {    
    this.refresher = refresher;
    this.memoryBean = memoryBean;
    this.heapDumper = heapDumper;
    
    threads = Collections.EMPTY_LIST;
    allocatedBytes = Collections.EMPTY_LIST;
    allocatedBytesPerSec = Collections.EMPTY_LIST;
    
    initComponents();
    
    addHierarchyListener(new HierarchyListener() {
        public void hierarchyChanged(HierarchyEvent e) {
            if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
                if (isShowing()) ThreadsMemoryView.this.refresher.refresh();
            }
        }
    });
}
 
Example #12
Source File: MemoryMonitor.java    From rice with Educational Community License v2.0 6 votes vote down vote up
public MemoryMonitor() {
    LOG.info("initializing");
    this.springContextId = "Unknown";
    MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    NotificationEmitter emitter = (NotificationEmitter) mbean;
    emitter.addNotificationListener(new NotificationListener() {
        public void handleNotification(Notification n, Object hb) {
            if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
                long maxMemory = tenuredGenPool.getUsage().getMax();
                long usedMemory = tenuredGenPool.getUsage().getUsed();
                for (Listener listener : listeners) {
                    listener.memoryUsageLow(springContextId, usedMemory, maxMemory);
                }
            }
        }
    }, null, null);
}
 
Example #13
Source File: MemoryView.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
MemoryView(Application application, AbstractSamplerSupport.Refresher refresher, int mode,
           MemoryMXBean memoryBean, MemorySamplerSupport.SnapshotDumper snapshotDumper,
           MemorySamplerSupport.HeapDumper heapDumper) {

    this.refresher = refresher;
    this.mode = mode;

    this.memoryBean = memoryBean;
    this.snapshotDumper = snapshotDumper;
    this.heapDumper = heapDumper;
    
    initComponents(application);

    addHierarchyListener(new HierarchyListener() {
        public void hierarchyChanged(HierarchyEvent e) {
            if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
                if (isShowing()) MemoryView.this.refresher.refresh();
            }
        }
    });
}
 
Example #14
Source File: MemoryProfilerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void profilerDoesOneGcAndNoSleepExceptInFinish() throws Exception {
  MemoryProfiler profiler = MemoryProfiler.instance();
  profiler.setStableMemoryParameters(
      new MemoryProfileStableHeapParameters.Converter().convert("3,10"));
  profiler.start(ByteStreams.nullOutputStream());
  MemoryMXBean bean = Mockito.mock(MemoryMXBean.class);
  RecordingSleeper sleeper = new RecordingSleeper();
  profiler.prepareBean(ProfilePhase.ANALYZE, bean, sleeper);
  assertThat(sleeper.sleeps).isEmpty();
  verify(bean, times(1)).gc();
  profiler.prepareBean(ProfilePhase.FINISH, bean, sleeper);
  assertThat(sleeper.sleeps)
      .containsExactly(Duration.ofSeconds(10), Duration.ofSeconds(10))
      .inOrder();
  verify(bean, times(4)).gc();
}
 
Example #15
Source File: MemoryProfiler.java    From bazel with Apache License 2.0 6 votes vote down vote up
public synchronized void markPhase(ProfilePhase nextPhase) throws InterruptedException {
  if (memoryProfile != null) {
    MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
    prepareBean(nextPhase, bean, (duration) -> Thread.sleep(duration.toMillis()));
    String name = currentPhase.description;
    MemoryUsage memoryUsage = bean.getHeapMemoryUsage();
    memoryProfile.println(name + ":heap:init:" + memoryUsage.getInit());
    memoryProfile.println(name + ":heap:used:" + memoryUsage.getUsed());
    memoryProfile.println(name + ":heap:commited:" + memoryUsage.getCommitted());
    memoryProfile.println(name + ":heap:max:" + memoryUsage.getMax());
    if (nextPhase == ProfilePhase.FINISH) {
      heapUsedMemoryAtFinish = memoryUsage.getUsed();
    }

    memoryUsage = bean.getNonHeapMemoryUsage();
    memoryProfile.println(name + ":non-heap:init:" + memoryUsage.getInit());
    memoryProfile.println(name + ":non-heap:used:" + memoryUsage.getUsed());
    memoryProfile.println(name + ":non-heap:commited:" + memoryUsage.getCommitted());
    memoryProfile.println(name + ":non-heap:max:" + memoryUsage.getMax());
    currentPhase = nextPhase;
  }
}
 
Example #16
Source File: RendererBenchmarkTest.java    From interviewcode with Apache License 2.0 6 votes vote down vote up
private void memory(Renderer renderer) {
  System.gc();
  MemoryMXBean mxbean = ManagementFactory.getMemoryMXBean();
  {
    long total = 0;
    for (int i = 0; i < 1000000; i++) {
      long start = mxbean.getHeapMemoryUsage().getUsed();
      renderer.render(text, entitiesList.get(i % 1000));
      long end = mxbean.getHeapMemoryUsage().getUsed();
      long diff = end - start;
      if (diff > 0) {
        total += diff;
      }
    }
    System.out.println("Memory: " + renderer.getClass().getSimpleName() + ": " + total / 1000000 + " bytes/op");
  }

}
 
Example #17
Source File: MemorySensor.java    From swage with Apache License 2.0 5 votes vote down vote up
private void reportHeapUsage(MemoryMXBean memoryMxBean, MetricContext metricContext) {
    MemoryUsage usage = memoryMxBean.getHeapMemoryUsage();

    long used = usage.getUsed();
    metricContext.record(HEAP, used / M, Unit.MEGABYTE);

    long max = usage.getMax();
    if (max >= 0) {
        metricContext.record(HEAP_MAX, max / M, Unit.MEGABYTE);

        double used_percent = 100.0 * ((double)used/(double)max);
        metricContext.record(HEAP_USED, used_percent, Unit.PERCENT);
    }
}
 
Example #18
Source File: MemorySensor.java    From swage with Apache License 2.0 5 votes vote down vote up
@Override
public void sense(final MetricContext metricContext)
{
    MemoryMXBean mxBean = ManagementFactory.getMemoryMXBean();

    reportHeapUsage(mxBean, metricContext);
    reportNonHeapUsage(mxBean, metricContext);
}
 
Example #19
Source File: GridManagerMxBeanIllegalArgumentHandleTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** Changes field to always failing mock. */
@Before
public void setUp() throws Exception {
    try {
        final MemoryMXBean memoryMXBean = createAlwaysFailingMxBean();
        memMxBeanField = createAccessibleMemField();
        mxBeanToRestore = memMxBeanField.get(null);
        memMxBeanField.set(null, memoryMXBean);

        correctSetupOfTestPerformed = memMxBeanField.get(null) == memoryMXBean;
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #20
Source File: MemorySensor.java    From swage with Apache License 2.0 5 votes vote down vote up
private void reportNonHeapUsage(MemoryMXBean memoryMxBean, MetricContext metricContext) {
    MemoryUsage usage = memoryMxBean.getNonHeapMemoryUsage();

    long used = usage.getUsed();
    metricContext.record(NON_HEAP, used / M, Unit.MEGABYTE);

    long max = usage.getMax();
    if (max >= 0) {
        metricContext.record(NON_HEAP_MAX, max / M, Unit.MEGABYTE);

        double used_percent = 100.0 * ((double)used/(double)max);
        metricContext.record(NON_HEAP_USED, used_percent, Unit.PERCENT);
    }
}
 
Example #21
Source File: KafkaServiceImpl.java    From kafka-eagle with Apache License 2.0 5 votes vote down vote up
/**
 * Get kafka os memory.
 */
public long getOSMemory(String host, int port, String property) {
	JMXConnector connector = null;
	long memory = 0L;
	String JMX = "service:jmx:rmi:///jndi/rmi://%s/jmxrmi";
	try {
		JMXServiceURL jmxSeriverUrl = new JMXServiceURL(String.format(JMX, host + ":" + port));
		connector = JMXFactoryUtils.connectWithTimeout(jmxSeriverUrl, 30, TimeUnit.SECONDS);
		MBeanServerConnection mbeanConnection = connector.getMBeanServerConnection();
		MemoryMXBean memBean = ManagementFactory.newPlatformMXBeanProxy(mbeanConnection, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
		long max = memBean.getHeapMemoryUsage().getMax();
		long used = memBean.getHeapMemoryUsage().getUsed();
		if (BrokerServer.TOTAL_PHYSICAL_MEMORY_SIZE.getValue().equals(property)) {
			memory = max;
		} else if (BrokerServer.FREE_PHYSICAL_MEMORY_SIZE.getValue().equals(property)) {
			memory = max - used;
		}
	} catch (Exception ex) {
		LOG.error("Get kafka os memory from jmx has error, msg is " + ex.getMessage());
	} finally {
		if (connector != null) {
			try {
				connector.close();
			} catch (IOException e) {
				LOG.error("Close kafka os memory jmx connector has error, msg is " + e.getMessage());
			}
		}
	}
	return memory;
}
 
Example #22
Source File: MemorySamplerSupport.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
public MemorySamplerSupport(Application application, Jvm jvm, boolean hasPermGen, ThreadsMemory mem, MemoryMXBean memoryBean, SnapshotDumper snapshotDumper, HeapDumper heapDumper) {
    this.application = application;
    
    this.jvm = jvm;
    hasPermGenHisto = hasPermGen;
    threadsMemory = mem;
    this.memoryBean = memoryBean;
    this.heapDumper = heapDumper;
    this.snapshotDumper = snapshotDumper;
}
 
Example #23
Source File: MXBeanInteropTest1.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private final int doMemoryMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- MemoryMXBean") ;

    try {
        ObjectName memoryName =
                new ObjectName(ManagementFactory.MEMORY_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(memoryName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t"
                + mbInfo);
        MemoryMXBean memory = null ;

        memory =
                JMX.newMXBeanProxy(mbsc,
                memoryName,
                MemoryMXBean.class,
                true) ;
        System.out.println("getMemoryHeapUsage\t\t"
                + memory.getHeapMemoryUsage());
        System.out.println("getNonHeapMemoryHeapUsage\t\t"
                + memory.getNonHeapMemoryUsage());
        System.out.println("getObjectPendingFinalizationCount\t\t"
                + memory.getObjectPendingFinalizationCount());
        System.out.println("isVerbose\t\t"
                + memory.isVerbose());

        System.out.println("---- OK\n") ;

    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example #24
Source File: GridManagerMxBeanIllegalArgumentHandleTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** MX bean which is always failing to respond with metrics */
@NotNull private MemoryMXBean createAlwaysFailingMxBean() {
    final Answer<MemoryUsage> failingAnswer = new Answer<MemoryUsage>() {
        @Override public MemoryUsage answer(InvocationOnMock invocationOnMock) throws Throwable {
            throw new IllegalArgumentException("java.lang.IllegalArgumentException: committed = 5274103808 should be < max = 5274095616");
        }
    };
    final MemoryMXBean memoryMXBean = Mockito.mock(MemoryMXBean.class);
    when(memoryMXBean.getHeapMemoryUsage()).thenAnswer(failingAnswer);
    when(memoryMXBean.getNonHeapMemoryUsage()).thenAnswer(failingAnswer);
    return memoryMXBean;
}
 
Example #25
Source File: GfxdConfigMessage.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public Object process(Object arg, Set<DistributedMember> members,
    GfxdConfigMessage<?> msg) {
  TreeMap<Object, Object> map = new TreeMap<Object, Object>();
  // GC information
  for (GarbageCollectorMXBean gcBean : ManagementFactory
      .getGarbageCollectorMXBeans()) {
    final String gcPrefix = "gc-" + gcBean.getName();
    map.put(gcPrefix + "-collection-count", gcBean.getCollectionCount());
    map.put(gcPrefix + "-collection-time", gcBean.getCollectionTime());
    map.put(gcPrefix + "-memory-pools",
        GemFireXDUtils.toCSV(gcBean.getMemoryPoolNames()));
  }
  // some thread information
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  map.put("thread-count", threadBean.getThreadCount());
  map.put("thread-total-count", threadBean.getTotalStartedThreadCount());
  map.put("thread-peak-count", threadBean.getPeakThreadCount());
  // some memory information
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage heapUsage = memBean.getHeapMemoryUsage();
  MemoryUsage nonHeapUsage = memBean.getNonHeapMemoryUsage();
  map.put("memory-heap-max", heapUsage.getMax());
  map.put("memory-heap-committed", heapUsage.getCommitted());
  map.put("memory-heap-used", heapUsage.getUsed());
  map.put("memory-nonheap-max", nonHeapUsage.getMax());
  map.put("memory-nonheap-committed", nonHeapUsage.getCommitted());
  map.put("memory-nonheap-used", nonHeapUsage.getUsed());
  // some more runtime memory information
  Runtime rt = Runtime.getRuntime();
  map.put("memory-free", rt.freeMemory());
  map.put("memory-max", rt.maxMemory());
  map.put("memory-total", rt.totalMemory());
  map.put("available-processors", rt.availableProcessors());
  return map;
}
 
Example #26
Source File: MXBeanInteropTest1.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private final int doMemoryMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- MemoryMXBean") ;

    try {
        ObjectName memoryName =
                new ObjectName(ManagementFactory.MEMORY_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(memoryName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t"
                + mbInfo);
        MemoryMXBean memory = null ;

        memory =
                JMX.newMXBeanProxy(mbsc,
                memoryName,
                MemoryMXBean.class,
                true) ;
        System.out.println("getMemoryHeapUsage\t\t"
                + memory.getHeapMemoryUsage());
        System.out.println("getNonHeapMemoryHeapUsage\t\t"
                + memory.getNonHeapMemoryUsage());
        System.out.println("getObjectPendingFinalizationCount\t\t"
                + memory.getObjectPendingFinalizationCount());
        System.out.println("isVerbose\t\t"
                + memory.isVerbose());

        System.out.println("---- OK\n") ;

    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example #27
Source File: JvmMetrics.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private void doMemoryUpdates() {
    MemoryMXBean memoryMXBean =
           ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap =
            memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap =
            memoryMXBean.getHeapMemoryUsage();
    Runtime runtime = Runtime.getRuntime();

    metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed()/M);
    metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted()/M);
    metrics.setMetric("memHeapUsedM", memHeap.getUsed()/M);
    metrics.setMetric("memHeapCommittedM", memHeap.getCommitted()/M);
    metrics.setMetric("maxMemoryM", runtime.maxMemory()/M);
}
 
Example #28
Source File: MXBeanInteropTest1.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private final int doMemoryMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- MemoryMXBean") ;

    try {
        ObjectName memoryName =
                new ObjectName(ManagementFactory.MEMORY_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(memoryName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t"
                + mbInfo);
        MemoryMXBean memory = null ;

        memory =
                JMX.newMXBeanProxy(mbsc,
                memoryName,
                MemoryMXBean.class,
                true) ;
        System.out.println("getMemoryHeapUsage\t\t"
                + memory.getHeapMemoryUsage());
        System.out.println("getNonHeapMemoryHeapUsage\t\t"
                + memory.getNonHeapMemoryUsage());
        System.out.println("getObjectPendingFinalizationCount\t\t"
                + memory.getObjectPendingFinalizationCount());
        System.out.println("isVerbose\t\t"
                + memory.isVerbose());

        System.out.println("---- OK\n") ;

    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example #29
Source File: JvmMetrics.java    From big-c with Apache License 2.0 5 votes vote down vote up
private void doMemoryUpdates() {
    MemoryMXBean memoryMXBean =
           ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap =
            memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap =
            memoryMXBean.getHeapMemoryUsage();
    Runtime runtime = Runtime.getRuntime();

    metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed()/M);
    metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted()/M);
    metrics.setMetric("memHeapUsedM", memHeap.getUsed()/M);
    metrics.setMetric("memHeapCommittedM", memHeap.getCommitted()/M);
    metrics.setMetric("maxMemoryM", runtime.maxMemory()/M);
}
 
Example #30
Source File: MemoryDataProvider.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
protected long getValueFromBean(Object bean) {
    if (type == TYPE_COMMITTED) {
        return ((MemoryMXBean) bean).getHeapMemoryUsage().getCommitted();
    } else {
        return ((MemoryMXBean) bean).getHeapMemoryUsage().getUsed();
    }
}