Java Code Examples for java.lang.management.MemoryMXBean

The following examples show how to use java.lang.management.MemoryMXBean. These examples are extracted from open source projects. 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 Project: bazel   Source File: MemoryProfilerTest.java    License: 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 2
Source Project: bazel   Source File: MemoryProfiler.java    License: 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 3
Source Project: nextreports-server   Source File: InfoUtil.java    License: 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 4
Source Project: joyqueue   Source File: GarbageCollectorMonitor.java    License: 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 5
@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 6
Source Project: rice   Source File: MemoryMonitor.java    License: 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 7
Source Project: game-server   Source File: SysUtil.java    License: 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 8
Source Project: appstatus   Source File: JvmCheck.java    License: 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 9
Source Project: bazel   Source File: IdleServerTasks.java    License: 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 10
Source Project: ClusterDeviceControlPlatform   Source File: Test.java    License: 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 11
Source Project: pitest   Source File: MemoryWatchdog.java    License: 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 12
Source Project: visualvm   Source File: ThreadsMemoryView.java    License: 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 13
Source Project: visualvm   Source File: MemoryView.java    License: 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 Project: visualvm   Source File: MemoryView.java    License: 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 15
Source Project: pravega   Source File: Main.java    License: 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 16
Source Project: interviewcode   Source File: RendererBenchmarkTest.java    License: 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 Project: bistoury   Source File: JVMTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void getVmInfo() throws Exception {
    VirtualMachine vm = VirtualMachine.attach(String.valueOf(10248));
    // 获得连接地址
    Properties properties = vm.getAgentProperties();
    String address = (String) properties.get("com.sun.management.jmxremote.localConnectorAddress");
    System.out.println(address);
    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector connector = JMXConnectorFactory.connect(url);
    RuntimeMXBean rmxb = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), "java.lang:type=Runtime", RuntimeMXBean.class);
    MemoryMXBean memoryMXBean = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
    System.out.println(operatingSystemMXBean.getSystemCpuLoad());
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
    Map<String, Object> result = new HashMap<>();
    //堆提交内存
    result.put("heapCommitedMemory", memoryUsage.getCommitted() / KB);
    //当前堆内存
    result.put("heapUsedMemory", memoryUsage.getUsed() / KB);
    //最大堆大小
    result.put("heapMaxMemory", memoryUsage.getMax() / KB);

    memoryUsage = memoryMXBean.getNonHeapMemoryUsage();
    //非堆提交内存
    result.put("nonHeapCommitedMemory", memoryUsage.getCommitted() / KB);
    //当前非堆内存
    result.put("nonHeapUsedMemory", memoryUsage.getUsed() / KB);
    //最大非堆大小
    result.put("nonHeapMaxMemory", memoryUsage.getMax() / KB);
    System.out.println(result);
    vm.detach();
}
 
Example 18
Source Project: unidbg   Source File: BaseVM.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final void printMemoryInfo() {
    System.gc();
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heap = memoryMXBean.getHeapMemoryUsage();
    MemoryUsage nonheap = memoryMXBean.getNonHeapMemoryUsage();
    System.err.println("globalObjectSize=" + globalObjectMap.size() + ", localObjectSize=" + localObjectMap.size() + ", classSize=" + classMap.size());
    System.err.println("heap: " + memoryUsage(heap) + ", nonheap: " + memoryUsage(nonheap));
}
 
Example 19
Source Project: Deta_Cache   Source File: OperatingSystemInfoUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * Java ��������ڴ�ϵͳ
	 */
	public static Map<String, String> showMemoryInfo() {
		Map<String, String> map = new HashMap<>();
		MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
		MemoryUsage heap = mem.getHeapMemoryUsage();
		map.put("Heap committed:", "" + heap.getCommitted());
		map.put("init:", "" + heap.getInit());
		map.put("max:", "" + heap.getMax());
		map.put("used:", "" + heap.getUsed());
		return map;
//		System.out.println("Heap committed:" + heap.getCommitted() + " init:" + heap.getInit() + " max:"
//				+ heap.getMax() + " used:" + heap.getUsed());
	}
 
Example 20
Source Project: chaosblade-exec-jvm   Source File: HeapJvmOomExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Long calculateCostMemoryInterval(JvmOomConfiguration jvmOomConfiguration) {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    long maxUsed = memoryMXBean.getHeapMemoryUsage().getMax();
    long heapUsed = memoryMXBean.getHeapMemoryUsage().getUsed();
    long left = maxUsed - heapUsed;
    long count = left / (JvmConstant.ONE_MB * jvmOomConfiguration.getBlock());
    long intervalInMillsecond = 0;
    if (count > 1) {
        intervalInMillsecond = MIN_TIME_COST_FILL_HEAP / count;
    }
    return intervalInMillsecond;
}
 
Example 21
Source Project: appstatus   Source File: JvmPropertyProvider.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, String> getProperties() {
    Map<String, String> map = new TreeMap<String, String>();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    List<String> aList = runtimeMXBean.getInputArguments();
    String parameters = "";
    for (int i = 0; i < aList.size(); i++) {
        parameters = parameters + " " + aList.get(i);
    }
    map.put("params", parameters);

    map.put("name", runtimeMXBean.getVmName());
    map.put("vendor", runtimeMXBean.getVmVendor());
    map.put("version", runtimeMXBean.getVmVersion());
    map.put("specification", runtimeMXBean.getSpecVersion());
    map.put("uptime", DurationFormatUtils.formatDurationHMS(runtimeMXBean.getUptime()));

    Date date = new Date(runtimeMXBean.getStartTime());
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    map.put("start time", sdf.format(date));

    MemoryMXBean memory = ManagementFactory.getMemoryMXBean();

    MemoryUsage heap = memory.getHeapMemoryUsage();
    map.put("memory. (heap)", readableFileSize(heap.getUsed()) + "/" + readableFileSize(heap.getCommitted()) + " min:" + readableFileSize(heap.getInit()) + " max:" + readableFileSize(heap.getMax()));
    MemoryUsage nonheap = memory.getNonHeapMemoryUsage();
    map.put("memory (non heap)", readableFileSize(nonheap.getUsed()) + "/" + readableFileSize(nonheap.getCommitted()) + " min:" + readableFileSize(nonheap.getInit()) + " max:" + readableFileSize(nonheap.getMax()));

    return map;
}
 
Example 22
Source Project: Jpom   Source File: InternalController.java    License: MIT License 5 votes vote down vote up
/**
 * 获取jvm内存
 *
 * @param tag tag
 * @return JSONObject
 */
private JSONObject getBeanMem(String tag) {
    try {
        MemoryMXBean bean = JvmUtil.getMemoryMXBean(tag);
        if (bean == null) {
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mount", bean.getObjectPendingFinalizationCount());
        //堆内存
        MemoryUsage memory = bean.getHeapMemoryUsage();
        //非堆内存
        MemoryUsage nonHeapMemoryUsage = bean.getNonHeapMemoryUsage();
        long used = memory.getUsed();
        long max = memory.getMax();
        //未定义
        if (-1 == max) {
            max = memory.getCommitted();
        }
        //计算使用内存占最大内存的百分比
        double v = new BigDecimal(used).divide(new BigDecimal(max), 2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
        jsonObject.put("heapUsed", FileUtil.readableFileSize(used));
        jsonObject.put("heapProportion", String.format("%.2f", v) + "%");
        jsonObject.put("heapCommitted", FileUtil.readableFileSize(memory.getCommitted()));
        long nonUsed = nonHeapMemoryUsage.getUsed();
        long nonMax = nonHeapMemoryUsage.getMax();
        long nonCommitted = nonHeapMemoryUsage.getCommitted();
        if (-1 == nonMax) {
            nonMax = nonCommitted;
        }
        jsonObject.put("nonHeapUsed", FileUtil.readableFileSize(nonUsed));
        double proportion = new BigDecimal(nonUsed).divide(new BigDecimal(nonMax), 2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
        jsonObject.put("nonHeapProportion", String.format("%.2f", proportion) + "%");
        jsonObject.put("nonHeapCommitted", FileUtil.readableFileSize(nonCommitted));
        return jsonObject;
    } catch (Exception e) {
        DefaultSystemLog.getLog().error(e.getMessage(), e);
    }
    return null;
}
 
Example 23
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 Project: bazel   Source File: MemoryProfilerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void profilerDoesOneGcAndNoSleepNormally() throws Exception {
  MemoryProfiler profiler = MemoryProfiler.instance();
  profiler.setStableMemoryParameters(
      new MemoryProfileStableHeapParameters.Converter().convert("1,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);
  verify(bean, times(2)).gc();
  assertThat(sleeper.sleeps).isEmpty();
}
 
Example 25
Source Project: joyrpc   Source File: JVMStatusTelnetHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TelnetResponse telnet(Channel channel, String[] args) {
    if (args != null && args.length != 0) {
        return new TelnetResponse(help());
    }
    StringBuilder sb = new StringBuilder(1024);
    //内存使用情况
    MemoryMXBean mmxb = ManagementFactory.getMemoryMXBean();
    long max = mmxb.getHeapMemoryUsage().getMax();
    long used = mmxb.getHeapMemoryUsage().getUsed();
    long init = mmxb.getHeapMemoryUsage().getInit();
    long commit = mmxb.getHeapMemoryUsage().getCommitted();
    sb.append("********Memory status******************").append(LINE);
    sb.append("Max JVM Heap Memory:").append(max / 1024 / 1024).append("M").append(LINE)
            .append("Used Heap Memory:").append(used / 1024 / 1024).append("M").append(LINE)
            .append("Init Heap Memory:").append(init / 1024 / 1024).append("M").append(LINE)
            .append("Commited Heap Memory:").append(commit / 1024 / 1024).append("M").append(LINE);

    sb.append("********Thread status********************").append(LINE);
    //线程数
    ThreadMXBean txmb = ManagementFactory.getThreadMXBean();
    sb.append("Peak thread count:").append(txmb.getPeakThreadCount()).append(LINE)
            .append("Thread count:").append(txmb.getThreadCount()).append(LINE);

    sb.append("********Runtime status******************").append(LINE);
    //启动入口参数
    RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
    sb.append("InputArguments:[");
    for (String ia : rmxb.getInputArguments()) {
        sb.append(ia).append(",");
    }
    sb.deleteCharAt(sb.length() - 1).append("]").append(LINE);

    DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
    LocalDateTime localDateTime = Instant.ofEpochMilli(rmxb.getStartTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    sb.append("JVM start time:").append(dtf.format(localDateTime)).append(LINE);

    return new TelnetResponse(sb.toString());
}
 
Example 26
Source Project: apm-agent-java   Source File: JvmMemoryMetrics.java    License: Apache License 2.0 5 votes vote down vote up
void bindTo(final MetricRegistry registry) {
    final MemoryMXBean platformMXBean = ManagementFactory.getPlatformMXBean(MemoryMXBean.class);
    registry.add("jvm.memory.heap.used", Labels.EMPTY, new DoubleSupplier() {
        @Override
        public double get() {
            return platformMXBean.getHeapMemoryUsage().getUsed();
        }
    });
    registry.add("jvm.memory.heap.committed", Labels.EMPTY, new DoubleSupplier() {
        @Override
        public double get() {
            return platformMXBean.getHeapMemoryUsage().getCommitted();
        }
    });
    registry.add("jvm.memory.heap.max", Labels.EMPTY, new DoubleSupplier() {
        @Override
        public double get() {
            return platformMXBean.getHeapMemoryUsage().getMax();
        }
    });
    registry.add("jvm.memory.non_heap.used", Labels.EMPTY, new DoubleSupplier() {
        @Override
        public double get() {
            return platformMXBean.getNonHeapMemoryUsage().getUsed();
        }
    });
    registry.add("jvm.memory.non_heap.committed", Labels.EMPTY, new DoubleSupplier() {
        @Override
        public double get() {
            return platformMXBean.getNonHeapMemoryUsage().getCommitted();
        }
    });
    registry.add("jvm.memory.non_heap.max", Labels.EMPTY, new DoubleSupplier() {
        @Override
        public double get() {
            return platformMXBean.getNonHeapMemoryUsage().getMax();
        }
    });
}
 
Example 27
Source Project: jvmtop   Source File: ProxyClient.java    License: GNU General Public License v2.0 5 votes vote down vote up
public synchronized MemoryMXBean getMemoryMXBean() throws IOException {
    if (hasPlatformMXBeans && memoryMBean == null) {
        memoryMBean =
            newPlatformMXBeanProxy(server, MEMORY_MXBEAN_NAME,
                                   MemoryMXBean.class);
    }
    return memoryMBean;
}
 
Example 28
public static double[] getHeap() {
	MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
	double u = mem.getHeapMemoryUsage().getUsed();
	double m = mem.getHeapMemoryUsage().getMax();
	double i = mem.getHeapMemoryUsage().getInit();
	return new double[] { i, u, m };
}
 
Example 29
public static String getNonHeap() {
	MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
	double c = 1.0 / (1024.0 * 1024.0);
	double u = mem.getNonHeapMemoryUsage().getUsed() * c;
	double m = mem.getNonHeapMemoryUsage().getMax() * c;
	double i = mem.getNonHeapMemoryUsage().getMax() * c;
	return String.format("u=%3.2f m=%3.2f i=%3.2f Mb", u, m, i);
}
 
Example 30
Source Project: emissary   Source File: WorkSpace.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check memory (heap) usage and wait for it to go below the threshold. We must be able to collect at least 500 file
 * bundles to trigger this mechanism.
 */
protected void pauseCollector() {
    final int initialQueueSize = getOutboundQueueSize();
    if (initialQueueSize < 500) {
        return;
    }
    final long intv = 30000;
    final MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heap = mbean.getHeapMemoryUsage();
    int count = 0;
    while ((((double) heap.getUsed() / (double) heap.getCommitted()) > WorkSpace.this.MEM_THRESHOLD) && (getOutboundQueueSize() > 500)) {
        logger.debug("Collection memory threshold exceeded " + heap);
        try {
            Thread.sleep(intv);
        } catch (InterruptedException ex) {
            // empty catch block
        }
        count++;
        heap = mbean.getHeapMemoryUsage();
    }

    if (count > 0 && logger.isDebugEnabled()) {
        logger.debug("Paused collector " + count + " times for " + (intv / 1000) + "s waiting for memory usage to " + "go below threshold "
                + WorkSpace.this.MEM_THRESHOLD + " resuming at " + heap + ", queueSize was/is=" + initialQueueSize + "/"
                + getOutboundQueueSize());
    }
}