Java Code Examples for java.lang.management.MemoryMXBean

The following are top voted examples for showing how to use java.lang.management.MemoryMXBean. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-servicecomb-java-chassis   File: MetricsServoRegistry.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 2
Project: traccar-service   File: Log.java   Source Code and License 6 votes vote down vote up
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");
    }
}
 
Example 3
Project: monarch   File: HeapMemoryMonitor.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Project: jsf-core   File: RegistryStatusServiceImpl.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 5
Project: baratine   File: KelpManagerBuilder.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 6
Project: venus   File: VMMonitor.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 7
Project: adeptj-runtime   File: ToolsServlet.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
}
 
Example 8
Project: javify   File: TestMemory.java   Source Code and License 6 votes vote down vote up
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"));
}
 
Example 9
Project: flink   File: MemoryLogger.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 10
Project: hadoop-EAR   File: ClusterStatus.java   Source Code and License 6 votes vote down vote up
/**
 * @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();
}
 
Example 11
Project: kc-rice   File: MemoryMonitor.java   Source Code and License 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 12
Project: jvm-stm   File: TestMemory.java   Source Code and License 6 votes vote down vote up
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"));
}
 
Example 13
Project: interviewcode   File: RendererBenchmarkTest.java   Source Code and License 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 14
Project: core-ng-project   File: MemoryUsageController.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 15
Project: mobac   File: MemoryTileCache.java   Source Code and License 6 votes vote down vote up
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));
		}
	}
}
 
Example 16
Project: app-framework   File: SysAdminUtilsImpl.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 17
Project: app-framework   File: SysAdminUtilsImpl.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 18
Project: search   File: StressRamUsageEstimator.java   Source Code and License 6 votes vote down vote up
@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.
  }
}
 
Example 19
Project: search   File: StressRamUsageEstimator.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 20
Project: sdcct   File: MemoryMetricSet.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 21
Project: Lucee4   File: MemoryControler.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 22
Project: tEFMA   File: AbstractDoubleDescriptionImpl.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 23
Project: Lucee   File: MemoryControler.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 24
Project: ktop   File: KTop.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 25
Project: blacksmith   File: MemoryUsageMonitor.java   Source Code and License 6 votes vote down vote up
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);
      }
   }
}
 
Example 26
Project: traccar-mongodb   File: Log.java   Source Code and License 6 votes vote down vote up
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");
    }
}
 
Example 27
Project: zico   File: SystemService.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 28
Project: JamVM-PH   File: TestMemory.java   Source Code and License 6 votes vote down vote up
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"));
}
 
Example 29
Project: wildfly-core   File: PlatformMBeanResourceUnitTestCase.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 30
Project: NYBC   File: StressRamUsageEstimator.java   Source Code and License 6 votes vote down vote up
@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.
  }
}
 
Example 31
Project: NYBC   File: StressRamUsageEstimator.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 32
Project: pitest   File: MemoryWatchdog.java   Source Code and License 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 33
Project: appstatus   File: JvmCheck.java   Source Code and License 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 34
Project: rice   File: MemoryMonitor.java   Source Code and License 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 35
Project: RDFS   File: ClusterStatus.java   Source Code and License 6 votes vote down vote up
/**
 * @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();
}
 
Example 36
Project: vs.msc.ws14   File: TaskManager.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 37
Project: classpath   File: TestMemory.java   Source Code and License 6 votes vote down vote up
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"));
}
 
Example 38
Project: kuali_rice   File: MemoryMonitor.java   Source Code and License 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 39
Project: Maskana-Gestor-de-Conocimiento   File: StressRamUsageEstimator.java   Source Code and License 6 votes vote down vote up
@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.
  }
}
 
Example 40
Project: Maskana-Gestor-de-Conocimiento   File: StressRamUsageEstimator.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 41
Project: nextreports-server   File: InfoUtil.java   Source Code and License 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 42
Project: swage   File: MemorySensor.java   Source Code and License 5 votes vote down vote up
@Override
public void sense(final MetricRecorder.Context metricContext)
{
    MemoryMXBean mxBean = ManagementFactory.getMemoryMXBean();

    reportHeapUsage(mxBean, metricContext);
    reportNonHeapUsage(mxBean, metricContext);
}
 
Example 43
Project: swage   File: MemorySensor.java   Source Code and License 5 votes vote down vote up
private void reportHeapUsage(MemoryMXBean memoryMxBean, MetricRecorder.Context 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 44
Project: swage   File: MemorySensor.java   Source Code and License 5 votes vote down vote up
private void reportNonHeapUsage(MemoryMXBean memoryMxBean, MetricRecorder.Context 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 45
Project: sstore-soft   File: SystemStatsCollector.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor accepts some system values and generates some Java values.
 *
 * @param rss Resident set size.
 */
Datum(long rss) {
    MemoryMXBean mmxb = ManagementFactory.getMemoryMXBean();
    MemoryUsage muheap = mmxb.getHeapMemoryUsage();
    MemoryUsage musys = mmxb.getNonHeapMemoryUsage();

    timestamp = System.currentTimeMillis();
    this.rss = rss;
    javatotalheapmem = muheap.getCommitted();
    javausedheapmem = muheap.getUsed();
    javatotalsysmem = musys.getCommitted();
    javausedsysmem = musys.getUsed();
}
 
Example 46
Project: hadoop-oss   File: JvmMetrics.java   Source Code and License 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 47
Project: newblog   File: JMXClient.java   Source Code and License 5 votes vote down vote up
public Long getJVMUsage() {
    MemoryMXBean memBean = null;
    try {
        memBean = ManagementFactory.newPlatformMXBeanProxy
                (mbsconnector, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
        MemoryUsage heap = memBean.getHeapMemoryUsage();
        return heap.getUsed();
    } catch (IOException e) {
        logger.error("", e);
        return 0L;
    }
}
 
Example 48
Project: convertigo-engine   File: UsageMonitor.java   Source Code and License 5 votes vote down vote up
public void run() {
	bContinue = true;
	
	try {
		while (bContinue) {
	        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
	        MemoryUsage memoryUsageHeap = memoryMXBean.getHeapMemoryUsage(); 
	        MemoryUsage memoryUsageNonHeap = memoryMXBean.getNonHeapMemoryUsage();
	        
	        setUsageCounter("[Memory] Heap memory usage", memoryUsageHeap);
	        setUsageCounter("[Memory] Non heap memory usage", memoryUsageNonHeap);
	        setUsageCounter("[Memory] Total used", (memoryUsageHeap.getUsed() + memoryUsageNonHeap.getUsed()) / 1024 + "K");
	        
			synchronized (usageCounters) {
				List<String> ls = new ArrayList<String>();
				ls.addAll(usageCounters.keySet());
				Collections.sort(ls);
				for (String counter : ls) {
					Engine.logUsageMonitor.info(counter + ": " + usageCounters.get(counter));
				}
			}
		
			Thread.sleep(30000);
		}
	} catch (NullPointerException npe) {
		if (Engine.theApp == null) {
			// Engine.theApp == null probably means the engine is getting stopped
			// so gracefully ignore and exit thread
			return;
		}
		else {
			npe.printStackTrace();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}

	usageCounters = null;
}
 
Example 49
Project: s-store   File: SystemStatsCollector.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor accepts some system values and generates some Java values.
 *
 * @param rss Resident set size.
 */
Datum(long rss) {
    MemoryMXBean mmxb = ManagementFactory.getMemoryMXBean();
    MemoryUsage muheap = mmxb.getHeapMemoryUsage();
    MemoryUsage musys = mmxb.getNonHeapMemoryUsage();

    timestamp = System.currentTimeMillis();
    this.rss = rss;
    javatotalheapmem = muheap.getCommitted();
    javausedheapmem = muheap.getUsed();
    javatotalsysmem = musys.getCommitted();
    javausedsysmem = musys.getUsed();
}
 
Example 50
Project: jsf-sdk   File: JVMStatusTelnetHandler.java   Source Code and License 5 votes vote down vote up
@Override
   public String telnet(Channel channel, String message) {
	StringBuilder sb = new StringBuilder();
	//内存使用情况
       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("").append(line)
               .append("Thread count:").append(txmb.getThreadCount()).append("").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);
       sb.append("JVM start time:").append(DateUtils.dateToStr(new Date(rmxb.getStartTime()))).append(line);
       
       return sb.toString();
}
 
Example 51
Project: ChronoBike   File: CodeManager.java   Source Code and License 5 votes vote down vote up
public static CodeSizeLimitEventHandler createSizeLimitEventHandler()
{
	MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
	NotificationEmitter emitter = (NotificationEmitter) mbean;
	CodeSizeLimitEventHandler eventHandler = new CodeSizeLimitEventHandler();
	return eventHandler;
}
 
Example 52
Project: hadoop   File: JvmMetrics.java   Source Code and License 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 53
Project: jdk8u-jdk   File: MXBeanInteropTest1.java   Source Code and License 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 54
Project: openjdk-jdk10   File: MXBeanInteropTest1.java   Source Code and License 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 55
Project: tqdev-metrics   File: SystemMonitor.java   Source Code and License 5 votes vote down vote up
private void registerMemoryStatistics() {
	final MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
	registry.set("jvm.Memory.Heap", "used", (Gauge) () -> mem.getHeapMemoryUsage().getUsed());
	registry.set("jvm.Memory.Heap", "init", (Gauge) () -> mem.getHeapMemoryUsage().getInit());
	registry.set("jvm.Memory.Heap", "max", (Gauge) () -> mem.getHeapMemoryUsage().getMax());
	registry.set("jvm.Memory.Heap", "comitted", (Gauge) () -> mem.getHeapMemoryUsage().getCommitted());
	registry.set("jvm.Memory.NonHeap", "used", (Gauge) () -> mem.getNonHeapMemoryUsage().getUsed());
	registry.set("jvm.Memory.NonHeap", "init", (Gauge) () -> mem.getNonHeapMemoryUsage().getInit());
	registry.set("jvm.Memory.NonHeap", "max", (Gauge) () -> mem.getNonHeapMemoryUsage().getMax());
	registry.set("jvm.Memory.NonHeap", "comitted", (Gauge) () -> mem.getNonHeapMemoryUsage().getCommitted());
}
 
Example 56
Project: java-memory-assistant   File: JavaVirtualMachine.java   Source Code and License 5 votes vote down vote up
@Override
public MemoryPool getHeapMemoryPool(final MemoryMXBean memoryBean) {
  return new MemoryPoolImpl(MemoryPool.Type.HEAP, new Supplier<MemoryUsage>() {
    @Override
    public MemoryUsage get() {
      return memoryBean.getHeapMemoryUsage();
    }
  });
}
 
Example 57
Project: java-memory-assistant   File: MBeanMonitorTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setup() throws Exception {
  memoryPoolBeans.clear();

  doReturn(0L).when(configuration).getCheckIntervalInMillis();

  doReturn(heapMemoryUsage).when(memoryBean).getHeapMemoryUsage();

  scheduler = spy(new DeterministicScheduler());
  doReturn(Collections.emptyList()).when(scheduler).shutdownNow();

  subject = spy(new MBeanMonitor(heapDumpCreator, configuration,
      new Callable<ScheduledExecutorService>() {
        @Override
        public ScheduledExecutorService call() throws Exception {
          return scheduler;
        }
      }, logger) {
    @Override
    MemoryMXBean getMemoryMxBean() {
      return memoryBean;
    }

    @Override
    List<MemoryPoolMXBean> getMemoryPoolMxBeans() {
      return memoryPoolBeans;
    }
  });

  doReturn(jvm).when(subject).findCurrentJvm();
}
 
Example 58
Project: java-performance   File: MemoryAndGC.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    System.out.println(">>>>> Memory");
    MemoryMXBean memoryMBean = ManagementFactory.getMemoryMXBean();
    System.out.println("Heap memory usage: " + memoryMBean.getHeapMemoryUsage());
    System.out.println("Non-Heap memory usage: " + memoryMBean.getNonHeapMemoryUsage());
    System.out.println("Objects pending finalization: " + memoryMBean.getObjectPendingFinalizationCount());

    System.out.println(">>>>> GC");
    ManagementFactory.getGarbageCollectorMXBeans().stream().forEach(bean -> {
        GarbageCollectorMXBean gcBean = (GarbageCollectorMXBean) bean;
        ((NotificationEmitter) gcBean).addNotificationListener(new GCLogger(), null, null);

        System.out.println(">> " + gcBean.getName());
        System.out.println("Collection count: " + gcBean.getCollectionCount());
        System.out.println("Collection time: " + gcBean.getCollectionTime());
        System.out.println("Last GC: " + gcBean.getLastGcInfo());
    });

    System.out.println(">>>>> Memory pool mbeans");
    ManagementFactory.getMemoryPoolMXBeans().stream().forEach(bean -> {
        System.out.println(">> " + bean.getName() + " " + bean.getType());
        System.out.println("Collection usage: " + bean.getCollectionUsage());
        System.out.println("Peak usage: " + bean.getPeakUsage());
        System.out.println("Usage: " + bean.getUsage());
        System.out.println("Memory manager names: " + Arrays.toString(bean.getMemoryManagerNames()));
    });


    while (true) {
        System.out.println("Allocating 1Mb");
        byte[] allocation = new byte[1024 * 1024];
        Thread.sleep(100);
    }
}
 
Example 59
Project: ditb   File: TestDefaultMemStore.java   Source Code and License 5 votes vote down vote up
/**
 * Test a pathological pattern that shows why we can't currently
 * use the MSLAB for upsert workloads. This test inserts data
 * in the following pattern:
 *
 * - row0001 through row1000 (fills up one 2M Chunk)
 * - row0002 through row1001 (fills up another 2M chunk, leaves one reference
 *   to the first chunk
 * - row0003 through row1002 (another chunk, another dangling reference)
 *
 * This causes OOME pretty quickly if we use MSLAB for upsert
 * since each 2M chunk is held onto by a single reference.
 */
public void testUpsertMSLAB() throws Exception {
  Configuration conf = HBaseConfiguration.create();
  conf.setBoolean(DefaultMemStore.USEMSLAB_KEY, true);
  memstore = new DefaultMemStore(conf, KeyValue.COMPARATOR);

  int ROW_SIZE = 2048;
  byte[] qualifier = new byte[ROW_SIZE - 4];

  MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
  for (int i = 0; i < 3; i++) { System.gc(); }
  long usageBefore = bean.getHeapMemoryUsage().getUsed();

  long size = 0;
  long ts=0;

  for (int newValue = 0; newValue < 1000; newValue++) {
    for (int row = newValue; row < newValue + 1000; row++) {
      byte[] rowBytes = Bytes.toBytes(row);
      size += memstore.updateColumnValue(rowBytes, FAMILY, qualifier, newValue, ++ts);
    }
  }
  System.out.println("Wrote " + ts + " vals");
  for (int i = 0; i < 3; i++) { System.gc(); }
  long usageAfter = bean.getHeapMemoryUsage().getUsed();
  System.out.println("Memory used: " + (usageAfter - usageBefore)
      + " (heapsize: " + memstore.heapSize() +
      " size: " + size + ")");
}
 
Example 60
Project: openjdk9   File: MXBeanInteropTest1.java   Source Code and License 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 ;
}