@Override public String call() { Map<String, String> memoryMap = new HashMap<>(); OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean(); double cpu = osMxBean.getSystemLoadAverage(); memoryMap.put("cpuLoad", String.format(doubleStringFormatter, round(cpu, doubleRoundPlaces))); ThreadMXBean threadmxBean = ManagementFactory.getThreadMXBean(); int threadCount = threadmxBean.getThreadCount(); memoryMap.put("cpuRunningThreads", String.valueOf(threadCount)); MemoryMXBean memBean = ManagementFactory.getMemoryMXBean(); MemoryUsage memHeapUsage = memBean.getHeapMemoryUsage(); MemoryUsage nonHeapUsage = memBean.getNonHeapMemoryUsage(); memoryMap.put("heapInit", String.valueOf(memHeapUsage.getInit())); memoryMap.put("heapMax", String.valueOf(memHeapUsage.getMax())); memoryMap.put("heapCommit", String.valueOf(memHeapUsage.getCommitted())); memoryMap.put("heapUsed", String.valueOf(memHeapUsage.getUsed())); memoryMap.put("nonHeapInit", String.valueOf(nonHeapUsage.getInit())); memoryMap.put("nonHeapMax", String.valueOf(nonHeapUsage.getMax())); memoryMap.put("nonHeapCommit", String.valueOf(nonHeapUsage.getCommitted())); memoryMap.put("nonHeapUsed", String.valueOf(nonHeapUsage.getUsed())); return memoryMap.toString(); }
public static void logSystemInfo() { try { OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean(); Log.info("Operating system" + " name: " + operatingSystemBean.getName() + " version: " + operatingSystemBean.getVersion() + " architecture: " + operatingSystemBean.getArch()); RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); Log.info("Java runtime" + " name: " + runtimeBean.getVmName() + " vendor: " + runtimeBean.getVmVendor() + " version: " + runtimeBean.getVmVersion()); MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); Log.info("Memory limit" + " heap: " + memoryBean.getHeapMemoryUsage().getMax() / (1024 * 1024) + "mb" + " non-heap: " + memoryBean.getNonHeapMemoryUsage().getMax() / (1024 * 1024) + "mb"); Log.info("Character encoding: " + System.getProperty("file.encoding") + " charset: " + Charset.defaultCharset()); } catch (Exception error) { Log.warning("Failed to get system info"); } }
/** * Register with the JVM to get threshold events. * * Package private for testing. */ void startJVMThresholdListener() { final MemoryPoolMXBean memoryPoolMXBean = getTenuredMemoryPoolMXBean(); // Set collection threshold to a low value, so that we can get // notifications after every GC run. After each such collection // threshold notification we set the usage thresholds to an // appropriate value. if (!testDisableMemoryUpdates) { memoryPoolMXBean.setCollectionUsageThreshold(1); } final long usageThreshold = memoryPoolMXBean.getUsageThreshold(); this.cache.getLoggerI18n().info( LocalizedStrings.HeapMemoryMonitor_OVERRIDDING_MEMORYPOOLMXBEAN_HEAP_0_NAME_1, new Object[] {Long.valueOf(usageThreshold), memoryPoolMXBean.getName()}); MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); NotificationEmitter emitter = (NotificationEmitter) mbean; emitter.addNotificationListener(this, null, null); }
@Override public String envi() { Map<String, String> result = new HashMap<String, String>(); // 系统信息 result.put(RegistryMonitorConstants.OSNAME, System.getProperty(RegistryMonitorConstants.OSNAME, "not specified")); result.put(RegistryMonitorConstants.JAVA_VERSION, System.getProperty(RegistryMonitorConstants.JAVA_VERSION, "not specified")); result.put(RegistryMonitorConstants.JDK_PATH, System.getProperty(RegistryMonitorConstants.JDK_PATH, "not specified")); result.put(RegistryMonitorConstants.APP_PATH, System.getProperty(RegistryMonitorConstants.APP_PATH, "not specified")); // jvm信息 MemoryMXBean memorymbean = ManagementFactory.getMemoryMXBean(); MemoryUsage usage = memorymbean.getHeapMemoryUsage(); result.put(RegistryMonitorConstants.JVM_INIT, String.valueOf(usage.getInit())); result.put(RegistryMonitorConstants.JVM_MAX, String.valueOf(usage.getMax())); result.put(RegistryMonitorConstants.JVM_USED, String.valueOf(usage.getUsed())); //线程信息 ThreadMXBean tm = (ThreadMXBean) ManagementFactory.getThreadMXBean(); result.put(RegistryMonitorConstants.JVM_THREAD_COUNT, String.valueOf(tm.getThreadCount())); result.put(RegistryMonitorConstants.JVM_PEAKTHREAD_COUNT, String.valueOf(tm.getPeakThreadCount())); result.put(RegistryMonitorConstants.JVM_CURRENTTHREAD_CPUTIME, String.valueOf(tm.getCurrentThreadCpuTime())); result.put(RegistryMonitorConstants.JVM_CURRENTTHREAD_USERTIME, String.valueOf(tm.getCurrentThreadUserTime())); return JSON.toJSONString(result); }
private static long getMaxMemory() { try { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heap = null; if (memoryBean != null) { heap = memoryBean.getHeapMemoryUsage(); } if (heap != null) { return Math.max(heap.getMax(), heap.getCommitted()); } else { Runtime runtime = Runtime.getRuntime(); return Math.max(runtime.maxMemory(), runtime.totalMemory()); } } catch (Exception e) { e.printStackTrace(); } return Runtime.getRuntime().maxMemory(); }
public String monitorMemory() { StringBuilder sb = new StringBuilder("Memory:"); MemoryMXBean mmbean = ManagementFactory.getMemoryMXBean(); MemoryUsage hmu = mmbean.getHeapMemoryUsage(); sb.append("[HeapMemoryUsage:"); sb.append(" Used=" + formatBytes(hmu.getUsed() * 8)); sb.append(" Committed=" + formatBytes(hmu.getCommitted() * 8)); sb.append("]"); MemoryUsage nhmu = mmbean.getNonHeapMemoryUsage(); sb.append("[NonHeapMemoryUsage:"); sb.append(" Used=" + formatBytes(nhmu.getUsed() * 8)); sb.append(" Committed=" + formatBytes(nhmu.getCommitted() * 8)); sb.append("]"); return sb.toString(); }
/** * Renders tools page. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Bundle[] bundles = BundleContextHolder.INSTANCE.getBundleContext().getBundles(); RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); TemplateEngine.getInstance().render(TemplateContext.builder() .request(req) .response(resp) .template(TOOLS_TEMPLATE) .locale(req.getLocale()) .contextObject(ContextObject.newContextObject() .put("username", req.getRemoteUser()) .put("sysProps", System.getProperties().entrySet()) .put("totalBundles", bundles.length) .put("bundles", bundles) .put("runtime", JAVA_RUNTIME_NAME + "(build " + JAVA_RUNTIME_VERSION + ")") .put("jvm", JAVA_VM_NAME + "(build " + JAVA_VM_VERSION + ", " + JAVA_VM_INFO + ")") .put("startTime", new Date(runtimeMXBean.getStartTime())) .put("upTime", TimeUnit.MILLISECONDS.toMinutes(runtimeMXBean.getUptime())) .put("maxMemory", FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getMax())) .put("usedMemory", FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getUsed())) .put("processors", Runtime.getRuntime().availableProcessors())) .build()); }
public static void main(String[] args) { MemoryMXBean bean = ManagementFactory.getMemoryMXBean(); System.out.println("Bean: " + bean); System.out.println("Heap memory usage: " + bean.getHeapMemoryUsage()); System.out.println("Non-heap memory usage: " + bean.getNonHeapMemoryUsage()); System.out.println("Objects pending finalization: " + bean.getObjectPendingFinalizationCount()); System.out.println("Running garbage collector via bean..."); bean.gc(); System.out.println("Heap memory usage: " + bean.getHeapMemoryUsage()); System.out.println("Non-heap memory usage: " + bean.getNonHeapMemoryUsage()); System.out.println("Objects pending finalization: " + bean.getObjectPendingFinalizationCount()); boolean verbosity = bean.isVerbose(); System.out.println("Verbose memory output: " + (verbosity ? "yes" : "no")); System.out.println("Changing verbose setting..."); bean.setVerbose(!verbosity); System.out.println("Verbose memory output: " + (bean.isVerbose() ? "yes" : "no")); }
/** * Gets the memory footprint of the JVM in a string representation. * * @return A string describing how much heap memory and direct memory are allocated and used. */ public static String getMemoryUsageStatsAsString(MemoryMXBean memoryMXBean) { MemoryUsage heap = memoryMXBean.getHeapMemoryUsage(); MemoryUsage nonHeap = memoryMXBean.getNonHeapMemoryUsage(); long heapUsed = heap.getUsed() >> 20; long heapCommitted = heap.getCommitted() >> 20; long heapMax = heap.getMax() >> 20; long nonHeapUsed = nonHeap.getUsed() >> 20; long nonHeapCommitted = nonHeap.getCommitted() >> 20; long nonHeapMax = nonHeap.getMax() >> 20; return String.format("Memory usage stats: [HEAP: %d/%d/%d MB, " + "NON HEAP: %d/%d/%d MB (used/committed/max)]", heapUsed, heapCommitted, heapMax, nonHeapUsed, nonHeapCommitted, nonHeapMax); }
/** * @param numDecommissionedNodes number of decommission trackers */ ClusterStatus(int trackers, int blacklists, long ttExpiryInterval, int maps, int reduces, int maxMaps, int maxReduces, JobTracker.State state, int numDecommissionedNodes) { numActiveTrackers = trackers; numBlacklistedTrackers = blacklists; this.numExcludedNodes = numDecommissionedNodes; this.ttExpiryInterval = ttExpiryInterval; map_tasks = maps; reduce_tasks = reduces; max_map_tasks = maxMaps; max_reduce_tasks = maxReduces; this.state = state; MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); MemoryUsage status = memoryMXBean.getHeapMemoryUsage(); used_memory = status.getUsed(); max_memory = status.getMax(); }
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); }
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"); } }
private MemoryUsage memoryUsage() { MemoryUsage usage = new MemoryUsage(); MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); java.lang.management.MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage(); usage.heapInit = heapMemoryUsage.getInit(); usage.heapUsed = heapMemoryUsage.getUsed(); usage.heapCommitted = heapMemoryUsage.getCommitted(); usage.heapMax = heapMemoryUsage.getMax(); java.lang.management.MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage(); usage.nonHeapInit = nonHeapMemoryUsage.getInit(); usage.nonHeapUsed = nonHeapMemoryUsage.getUsed(); usage.nonHeapCommitted = nonHeapMemoryUsage.getCommitted(); usage.nonHeapMax = nonHeapMemoryUsage.getMax(); return usage; }
public MemoryTileCache() { log = Logger.getLogger(this.getClass()); hashtable = new Hashtable<String, CacheEntry>(cacheSize); lruTiles = new CacheLinkedListElement(); cacheSize = 500; MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); NotificationBroadcaster emitter = (NotificationBroadcaster) mbean; emitter.addNotificationListener(this, null, null); // Set-up each memory pool to notify if the free memory falls below 10% for (MemoryPoolMXBean memPool : ManagementFactory.getMemoryPoolMXBeans()) { if (memPool.isUsageThresholdSupported()) { MemoryUsage memUsage = memPool.getUsage(); memPool.setUsageThreshold((long) (memUsage.getMax() * 0.95)); } } }
@Override public long[] getMaxSystemParameters() { long[] systemData = new long[3]; MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); systemData[0] = memoryMXBean.getHeapMemoryUsage().getMax(); systemData[1] = memoryMXBean.getNonHeapMemoryUsage().getMax(); List<MemoryPoolMXBean> mbeans = ManagementFactory.getMemoryPoolMXBeans(); if (mbeans != null) { for (MemoryPoolMXBean mbean : mbeans) { MemoryUsage memUsage = mbean.getUsage(); if (mbean.getName().equals(PERMGEN_MEMORY_POOL_NAME)) { systemData[2] = memUsage.getMax(); } } } return systemData; }
@Override public long[] getSystemStatus() { long[] systemData = new long[4]; MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); systemData[0] = memoryMXBean.getHeapMemoryUsage().getUsed(); systemData[1] = memoryMXBean.getNonHeapMemoryUsage().getUsed(); List<MemoryPoolMXBean> mbeans = ManagementFactory.getMemoryPoolMXBeans(); if (mbeans != null) { for (MemoryPoolMXBean mbean : mbeans) { MemoryUsage memUsage = mbean.getUsage(); if (mbean.getName().equals(PERMGEN_MEMORY_POOL_NAME)) { systemData[2] = memUsage.getUsed(); } } } ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); systemData[3] = threadMXBean.getThreadCount(); return systemData; }
@Ignore public void testChainedEstimation() { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); Random rnd = random(); Entry first = new Entry(); try { while (true) { // Check the current memory consumption and provide the estimate. long jvmUsed = memoryMXBean.getHeapMemoryUsage().getUsed(); long estimated = RamUsageTester.sizeOf(first); System.out.println(String.format(Locale.ROOT, "%10d, %10d", jvmUsed, estimated)); // Make a batch of objects. for (int i = 0; i < 5000; i++) { first.createNext(new byte[rnd.nextInt(1024)]); } } } catch (OutOfMemoryError e) { // Release and quit. } }
public void testLargeSetOfByteArrays() { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); causeGc(); long before = memoryMXBean.getHeapMemoryUsage().getUsed(); Object [] all = new Object [1000000]; for (int i = 0; i < all.length; i++) { all[i] = new byte[random().nextInt(3)]; } causeGc(); long after = memoryMXBean.getHeapMemoryUsage().getUsed(); System.out.println("mx: " + RamUsageEstimator.humanReadableUnits(after - before)); System.out.println("rue: " + RamUsageEstimator.humanReadableUnits(shallowSizeOf(all))); guard = all; }
@Override public Map<String, Metric> getMetrics() { Map<String, Metric> metrics = super.getMetrics(); MemoryMXBean memMxBean = ManagementFactory.getMemoryMXBean(); registerGauge(metrics, MEMORY_OBJ_PENDING_FINALIZATION_COUNT_METRIC_NAME, memMxBean.getObjectPendingFinalizationCount()); MemoryUsage heapMemUsage = memMxBean.getHeapMemoryUsage(), nonHeapMemUsage = memMxBean.getNonHeapMemoryUsage(); registerMemoryUsageMetrics(metrics, MEMORY_HEAP_METRIC_NAME_PREFIX, heapMemUsage); registerMemoryUsageMetrics(metrics, MEMORY_NON_HEAP_METRIC_NAME_PREFIX, nonHeapMemUsage); registerMemoryUsageMetrics(metrics, MEMORY_TOTAL_METRIC_NAME_PREFIX, (heapMemUsage.getCommitted() + nonHeapMemUsage.getCommitted()), (heapMemUsage.getInit() + nonHeapMemUsage.getInit()), -1, (heapMemUsage.getUsed() + nonHeapMemUsage.getUsed()), (heapMemUsage.getMax() + nonHeapMemUsage.getMax())); ManagementFactory.getMemoryPoolMXBeans().stream().filter(MemoryPoolMXBean::isValid) .forEach(memPoolMxBean -> registerMemoryPoolMetrics(metrics, memPoolMxBean)); ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class).stream().forEach(bufferPoolMxBean -> registerBufferPoolMetrics(metrics, bufferPoolMxBean)); return metrics; }
public synchronized static void init(ConfigServer cs){ if(init) return; // set level for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { types.put(pool.getName(), pool.getType()); // I don't know whether this approach is better, or whether // we should rather check for the pool name "Tenured Gen"? if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) { long maxMemory = pool.getUsage().getMax(); long warningThreshold = (long) (maxMemory * 0.9); //long warningThreshold = maxMemory -(10*1024*1024); pool.setUsageThreshold(warningThreshold); } } MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); NotificationEmitter emitter = (NotificationEmitter) mbean; MemoryNotificationListener listener = new MemoryNotificationListener(types); emitter.addNotificationListener(listener, null, cs); init=true; }
private void logOptions(MetabolicNetwork metaNet, EfmOutputCallback callback) { final RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean(); final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean(); final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); LOG.info("Elemetary flux mode computation"); LOG.info("Implementation:"); LOG.info("..algorithm name : " + getImplName()); LOG.info("..model type : " + getFactoryName(mEfmModelFactory)); LOG.info("..memory type : " + getFactoryName(mMemoryFactory)); LOG.info("..output type : " + getCallbackName(callback)); LOG.info("System:"); LOG.info("..hostname : " + getHostName()); LOG.info("..operating system : " + osBean.getArch() + "/" + osBean.getName() + "/" + osBean.getVersion()); LOG.info("..processors : " + osBean.getAvailableProcessors()); LOG.info("..vm : " + rtBean.getVmVendor() + "/" + rtBean.getVmName() + "/" + rtBean.getVmVersion()); LOG.info("..vm-spec : " + rtBean.getSpecVendor() + "/" + rtBean.getSpecName() + "/" + rtBean.getSpecVersion()); LOG.info("..vm arguments : " + rtBean.getInputArguments()); LOG.info("..memory, commited : " + (memBean.getHeapMemoryUsage().getCommitted() / 1000 / 1000) + "M"); LOG.info("..memory, used : " + (memBean.getHeapMemoryUsage().getUsed() / 1000 / 1000) + "M"); mConfig.log(LOG, Level.INFO); }
protected Object doExecute() throws Exception { if (numThreads != null) { numberOfDisplayedThreads = Integer.parseInt(numThreads); } if (updates != null) { DEFAULT_REFRESH_INTERVAL = Integer.parseInt(updates); } try { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); ThreadMXBean threads = ManagementFactory.getThreadMXBean(); MemoryMXBean mem = ManagementFactory.getMemoryMXBean(); ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean(); KTop(runtime, os, threads, mem, cl); } catch (IOException e) { //Ignore } return null; }
public void run() { if (running) { try { MBeanServerConnection con = ManagementFactory.getPlatformMBeanServer(); if (con == null) throw new IllegalStateException("PlatformMBeanServer not started!"); MemoryMXBean memMbean = ManagementFactory.newPlatformMXBeanProxy(con, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class); MemoryUsage mem = memMbean.getHeapMemoryUsage(); genUsed = mem.getUsed(); genCapacity = mem.getCommitted(); genMaxCapacity = mem.getMax(); addMeasurement(new BigDecimal(genUsed)); log.trace("Memory usage: used=" + formatDecimal(genUsed) + " B, size=" + formatDecimal(genCapacity) + " B, max=" + formatDecimal(genMaxCapacity)); } catch (Exception e) { log.error("Error in JMX memory stats retrieval", e); } } }
public static void logSystemInfo() { try { OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean(); Log.info("Operating System" + " name: " + operatingSystemBean.getName() + " version: " + operatingSystemBean.getVersion() + " architecture: " + operatingSystemBean.getArch()); RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); Log.info("Java Runtime" + " name: " + runtimeBean.getVmName() + " vendor: " + runtimeBean.getVmVendor() + " version: " + runtimeBean.getVmVersion()); MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); Log.info("Memory Limit" + " heap: " + memoryBean.getHeapMemoryUsage().getMax() / (1024 * 1024) + "mb" + " non-heap: " + memoryBean.getNonHeapMemoryUsage().getMax() / (1024 * 1024) + "mb"); } catch (Exception e) { Log.warning("Failed to get system info"); } }
@GET @Path("/info") public SystemInfo systemInfo() { SystemInfo info = new SystemInfo(); MemoryMXBean mem = ManagementFactory.getMemoryMXBean(); info.setTotalHeapMem(mem.getHeapMemoryUsage().getMax()); info.setUsedHeapMem(mem.getHeapMemoryUsage().getUsed()); info.setTotalNonHeapMem(mem.getNonHeapMemoryUsage().getMax()); info.setUsedNonHeapMem(mem.getNonHeapMemoryUsage().getUsed()); info.setUptime(ManagementFactory.getRuntimeMXBean().getUptime()); return info; }
@Test public void testMemoryMXBean() throws IOException { DescribedResource describedResource = basicResourceTest("memory", null); MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); boolean verbose = describedResource.resource.get("verbose").asBoolean(); Assert.assertEquals(mbean.isVerbose(), verbose); ModelNode op = getOperation("write-attribute", "memory", null); op.get("name").set("verbose"); op.get("value").set(!verbose); executeOp(op, false); Assert.assertEquals(mbean.isVerbose(), !verbose); // Restore mbean.setVerbose(verbose); op = getOperation("gc", "memory", null); Assert.assertFalse(executeOp(op, false).isDefined()); }
@Ignore public void testChainedEstimation() { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); Random rnd = random(); Entry first = new Entry(); try { while (true) { // Check the current memory consumption and provide the estimate. long jvmUsed = memoryMXBean.getHeapMemoryUsage().getUsed(); long estimated = RamUsageEstimator.sizeOf(first); System.out.println(String.format(Locale.ROOT, "%10d, %10d", jvmUsed, estimated)); // Make a batch of objects. for (int i = 0; i < 5000; i++) { first.createNext(new byte[rnd.nextInt(1024)]); } } } catch (OutOfMemoryError e) { // Release and quit. } }
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); } } }
@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(); }
private String getMemoryUsageStatsAsString(MemoryMXBean memoryMXBean) { MemoryUsage heap = memoryMXBean.getHeapMemoryUsage(); MemoryUsage nonHeap = memoryMXBean.getNonHeapMemoryUsage(); int mb = 1 << 20; int heapUsed = (int) (heap.getUsed() / mb); int heapCommitted = (int) (heap.getCommitted() / mb); int heapMax = (int) (heap.getMax() / mb); int nonHeapUsed = (int) (nonHeap.getUsed() / mb); int nonHeapCommitted = (int) (nonHeap.getCommitted() / mb); int nonHeapMax = (int) (nonHeap.getMax() / mb); String msg = String.format("Memory usage stats: [HEAP: %d/%d/%d MB, NON HEAP: %d/%d/%d MB (used/comitted/max)]", heapUsed, heapCommitted, heapMax, nonHeapUsed, nonHeapCommitted, nonHeapMax); return msg; }