Java Code Examples for java.lang.management.MemoryMXBean.getHeapMemoryUsage()

The following are Jave code examples for showing how to use getHeapMemoryUsage() of the java.lang.management.MemoryMXBean class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-servicecomb-java-chassis   File: MetricsServoRegistry.java   View Source Code Vote up 6 votes
@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: jsf-core   File: RegistryStatusServiceImpl.java   View Source Code Vote up 6 votes
@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 3
Project: baratine   File: KelpManagerBuilder.java   View Source Code Vote up 6 votes
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 4
Project: venus   File: VMMonitor.java   View Source Code Vote up 6 votes
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 5
Project: flink   File: MemoryLogger.java   View Source Code Vote up 6 votes
/**
 * 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 6
Project: hadoop-EAR   File: ClusterStatus.java   View Source Code Vote up 6 votes
/**
 * @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 7
Project: core-ng-project   File: MemoryUsageController.java   View Source Code Vote up 6 votes
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 8
Project: sdcct   File: MemoryMetricSet.java   View Source Code Vote up 6 votes
@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 9
Project: vs.msc.ws14   File: TaskManager.java   View Source Code Vote up 6 votes
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 10
Project: appstatus   File: JvmCheck.java   View Source Code Vote up 6 votes
@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 11
Project: RDFS   File: ClusterStatus.java   View Source Code Vote up 6 votes
/**
 * @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 12
Project: swage   File: MemorySensor.java   View Source Code Vote up 5 votes
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 13
Project: sstore-soft   File: SystemStatsCollector.java   View Source Code Vote up 5 votes
/**
 * 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 14
Project: hadoop-oss   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 15
Project: newblog   File: JMXClient.java   View Source Code Vote up 5 votes
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 16
Project: convertigo-engine   File: UsageMonitor.java   View Source Code Vote up 5 votes
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 17
Project: s-store   File: SystemStatsCollector.java   View Source Code Vote up 5 votes
/**
 * 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 18
Project: hadoop   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 19
Project: java-memory-assistant   File: JavaVirtualMachine.java   View Source Code Vote up 5 votes
@Override
public MemoryPool getHeapMemoryPool(final MemoryMXBean memoryBean) {
  return new MemoryPoolImpl(MemoryPool.Type.HEAP, new Supplier<MemoryUsage>() {
    @Override
    public MemoryUsage get() {
      return memoryBean.getHeapMemoryUsage();
    }
  });
}
 
Example 20
Project: aliyun-oss-hadoop-fs   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 21
Project: Jinseng-Server   File: StatusReporter.java   View Source Code Vote up 5 votes
public void PrintSystemMemoryUsage(){
       MemoryMXBean membean = ManagementFactory.getMemoryMXBean( );
       MemoryUsage heap = membean.getHeapMemoryUsage( );
       System.out.println( "Heap Memory: " + heap.toString( ) );
       MemoryUsage nonheap = membean.getNonHeapMemoryUsage( );
       System.out.println( "NonHeap Memory: " + nonheap.toString( ) );


}
 
Example 22
Project: Gargoyle   File: CPUUsageTest.java   View Source Code Vote up 5 votes
public void showMemory() {
	MemoryMXBean membean = ManagementFactory.getMemoryMXBean();
	MemoryUsage heap = membean.getHeapMemoryUsage();
	System.out.println("Heap Memory: " + heap.toString());
	MemoryUsage nonheap = membean.getNonHeapMemoryUsage();
	System.out.println("NonHeap Memory: " + nonheap.toString());
}
 
Example 23
Project: gemfirexd-oss   File: GfxdConfigMessage.java   View Source Code Vote up 5 votes
@Override
public Object process(Object arg, Set<DistributedMember> members,
    GfxdConfigMessage<?> msg) {
  TreeMap<Object, Object> map = new TreeMap<Object, Object>();
  // GC information
  for (GarbageCollectorMXBean gcBean : ManagementFactory
      .getGarbageCollectorMXBeans()) {
    final String gcPrefix = "gc-" + gcBean.getName();
    map.put(gcPrefix + "-collection-count", gcBean.getCollectionCount());
    map.put(gcPrefix + "-collection-time", gcBean.getCollectionTime());
    map.put(gcPrefix + "-memory-pools",
        GemFireXDUtils.toCSV(gcBean.getMemoryPoolNames()));
  }
  // some thread information
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  map.put("thread-count", threadBean.getThreadCount());
  map.put("thread-total-count", threadBean.getTotalStartedThreadCount());
  map.put("thread-peak-count", threadBean.getPeakThreadCount());
  // some memory information
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage heapUsage = memBean.getHeapMemoryUsage();
  MemoryUsage nonHeapUsage = memBean.getNonHeapMemoryUsage();
  map.put("memory-heap-max", heapUsage.getMax());
  map.put("memory-heap-committed", heapUsage.getCommitted());
  map.put("memory-heap-used", heapUsage.getUsed());
  map.put("memory-nonheap-max", nonHeapUsage.getMax());
  map.put("memory-nonheap-committed", nonHeapUsage.getCommitted());
  map.put("memory-nonheap-used", nonHeapUsage.getUsed());
  // some more runtime memory information
  Runtime rt = Runtime.getRuntime();
  map.put("memory-free", rt.freeMemory());
  map.put("memory-max", rt.maxMemory());
  map.put("memory-total", rt.totalMemory());
  map.put("available-processors", rt.availableProcessors());
  return map;
}
 
Example 24
Project: big-c   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 25
Project: hadoop-2.6.0-cdh5.4.3   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 26
Project: hadoop-EAR   File: JspHelper.java   View Source Code Vote up 5 votes
public String getInodeLimitText() {
  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();
  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();

  MemoryUsage heap = mem.getHeapMemoryUsage();
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();

  long totalHeap = heap.getUsed();
  long maxHeap = heap.getMax();
  long commitedHeap = heap.getCommitted();
  long initHeap = heap.getInit();

  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalHeap * 100)/maxHeap;
  long usedNonHeap = (totalNonHeap * 100) / maxNonHeap;


  String str = inodes + " files and directories, " +
               blocks + " blocks = " +
               (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100)/maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".  Heap Size is " + StringUtils.byteDesc(totalHeap) + " / "
      + StringUtils.byteDesc(maxHeap) + " (" + used + "%). Commited Heap: "
      + StringUtils.byteDesc(commitedHeap) + ". Init Heap: "
      + StringUtils.byteDesc(initHeap) + ". <br>";
  str += " Non Heap Memory Size is " + StringUtils.byteDesc(totalNonHeap)
      + " / " + StringUtils.byteDesc(maxNonHeap)
      + " (" + usedNonHeap + "%). Commited Non Heap: "
      + StringUtils.byteDesc(commitedNonHeap) + ".<br>";
  return str;
}
 
Example 27
Project: VoltDB   File: SystemStatsCollector.java   View Source Code Vote up 5 votes
/**
 * 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 28
Project: search   File: StressRamUsageEstimator.java   View Source Code Vote up 5 votes
public void testSimpleByteArrays() {
  MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

  Object [][] all = new Object [0][];
  try {
    while (true) {
      // Check the current memory consumption and provide the estimate.
      causeGc();
      MemoryUsage mu = memoryMXBean.getHeapMemoryUsage();
      long estimated = shallowSizeOf(all);
      if (estimated > 50 * RamUsageEstimator.ONE_MB) {
        break;
      }

      System.out.println(String.format(Locale.ROOT, "%10s\t%10s\t%10s", 
          RamUsageEstimator.humanReadableUnits(mu.getUsed()),
          RamUsageEstimator.humanReadableUnits(mu.getMax()), 
          RamUsageEstimator.humanReadableUnits(estimated)));

      // Make another batch of objects.
      Object[] seg =  new Object[10000];
      all = Arrays.copyOf(all, all.length + 1);
      all[all.length - 1] = seg;
      for (int i = 0; i < seg.length; i++) {
        seg[i] = new byte[random().nextInt(7)];
      }
    }
  } catch (OutOfMemoryError e) {
    // Release and quit.
  }
}
 
Example 29
Project: sinkit-core   File: WebApiEJB.java   View Source Code Vote up 5 votes
@Override
public String sayHello(final String queryString) {
    final OperatingSystemMXBean osmxbean = ManagementFactory.getOperatingSystemMXBean();
    final MemoryMXBean memxbean = ManagementFactory.getMemoryMXBean();
    final double load = osmxbean.getSystemLoadAverage() / osmxbean.getAvailableProcessors();
    final MemoryUsage mamUsage = memxbean.getHeapMemoryUsage();
    final long maxMem = mamUsage.getMax();
    final double usedmem = mamUsage.getUsed();
    return String.join(",", "Hello there ", queryString, ". My CPU load is ", Double.toString(load), "my heap mem usage is ", Double.toString(usedmem / ((maxMem >= 0) ? maxMem : mamUsage.getCommitted())));
}
 
Example 30
Project: hops   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 31
Project: RDFS   File: JspHelper.java   View Source Code Vote up 5 votes
public String getInodeLimitText() {
  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();
  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();

  MemoryUsage heap = mem.getHeapMemoryUsage();
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();

  long totalHeap = heap.getUsed();
  long maxHeap = heap.getMax();
  long commitedHeap = heap.getCommitted();
  long initHeap = heap.getInit();

  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalHeap * 100)/maxHeap;
  long usedNonHeap = (totalNonHeap * 100) / maxNonHeap;


  String str = inodes + " files and directories, " +
               blocks + " blocks = " +
               (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100)/maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".  Heap Size is " + StringUtils.byteDesc(totalHeap) + " / "
      + StringUtils.byteDesc(maxHeap) + " (" + used + "%). Commited Heap: "
      + StringUtils.byteDesc(commitedHeap) + ". Init Heap: "
      + StringUtils.byteDesc(initHeap) + ". <br>";
  str += " Non Heap Memory Size is " + StringUtils.byteDesc(totalNonHeap)
      + " / " + StringUtils.byteDesc(maxNonHeap)
      + " (" + usedNonHeap + "%). Commited Non Heap: "
      + StringUtils.byteDesc(commitedNonHeap) + ".<br>";
  return str;
}
 
Example 32
Project: hadoop-TCP   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 33
Project: cn1   File: ManagementFactoryTest.java   View Source Code Vote up 5 votes
public void testNewPlatformMXBeanProxy_MemoryMXBean() throws Exception {
    MemoryMXBean proxy = ManagementFactory.newPlatformMXBeanProxy(
            ManagementFactory.getPlatformMBeanServer(),
            "java.lang:type=Memory", MemoryMXBean.class);
    assertNotNull(proxy);
    MemoryMXBean mb = ManagementFactory.getMemoryMXBean();
    // RI's MemoryUsage does not appear to override equals() so we have to
    // go the long way round to check that the answers match...
    MemoryUsage mu1 = mb.getHeapMemoryUsage();
    MemoryUsage mu2 = proxy.getHeapMemoryUsage();
    assertEquals(mu1.getInit(), mu2.getInit());
    assertEquals(mu1.getMax(), mu2.getMax());

    mu1 = mb.getNonHeapMemoryUsage();
    mu2 = proxy.getNonHeapMemoryUsage();
    assertEquals(mu1.getInit(), mu2.getInit());
    assertEquals(mu1.getMax(), mu2.getMax());

    assertEquals(mb.isVerbose(), proxy.isVerbose());
    // changes made to proxy should be seen in the "real bean" and
    // vice versa
    boolean initialValue = proxy.isVerbose();
    mb.setVerbose(!initialValue);
    assertEquals(!initialValue, proxy.isVerbose());
    proxy.setVerbose(initialValue);
    assertEquals(initialValue, mb.isVerbose());
}
 
Example 34
Project: BlueTrader-E2E-Bluemix   File: CpuStressTest.java   View Source Code Vote up 5 votes
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 
	OperatingSystemMXBean osBean=ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
	
	MemoryMXBean mmBean = ManagementFactory.getMemoryMXBean();
	response.setContentType("text/plain");
	response.setStatus(200);
	PrintWriter writer = response.getWriter();
	//writer.println("Hello from "+System.getenv("VCAP_APP_HOST") + ":" + System.getenv("VCAP_APP_PORT"));
	//nthPrime(10000);
	nthPrime(1000);
	writer.println("---------------------------------------------------------------------");
	writer.println("CPU Stress Test");
	writer.println("---------------------------------------------------------------------");		
	writer.println("Available Processors	: "+osBean.getAvailableProcessors());
	writer.println("System Cpu Load		: "+Math.round(osBean.getSystemCpuLoad()*100)+"%");
	writer.println("Total Physical Memory	: "+Math.round((osBean.getTotalPhysicalMemory()/1024)/1024)+" (MB)");
	writer.println("Free Physical Memory	: "+Math.round((osBean.getFreePhysicalMemorySize()/1024)/1024)+" (MB)");
	MemoryUsage mu = mmBean.getHeapMemoryUsage();
	
	writer.println("Maximum heap		: "+Math.round((mu.getMax()/1024)/1024)+" (MB)");
	writer.println("Initial heap		: "+Math.round((mu.getInit()/1024)/1024)+" (MB)");
	int currentUsage=Math.round((mu.getUsed()/1024)/1024);		
	writer.println("Used heap		: "+currentUsage+" (MB)");
	if (currentUsage>highestHeapUsage) {
		highestHeapUsage=currentUsage;
	}
	writer.println("Highest heap		: "+highestHeapUsage+" (MB)");
	
	writer.close();
}
 
Example 35
Project: NeverwinterDP-Commons   File: MemoryInfo.java   View Source Code Vote up 5 votes
public MemoryInfo() {
  MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
  MemoryUsage memory = mbean.getHeapMemoryUsage() ;
  
  init = NumberFormatter.byteFormatAsHumanReadable(memory.getInit()) ;
  max = NumberFormatter.byteFormatAsHumanReadable(memory.getMax()) ;
  use = NumberFormatter.byteFormatAsHumanReadable(memory.getUsed()) ;
  committed = NumberFormatter.byteFormatAsHumanReadable(memory.getCommitted()) ;
  
}
 
Example 36
Project: NYBC   File: StressRamUsageEstimator.java   View Source Code Vote up 5 votes
public void testSimpleByteArrays() {
  MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

  Object [][] all = new Object [0][];
  try {
    while (true) {
      // Check the current memory consumption and provide the estimate.
      causeGc();
      MemoryUsage mu = memoryMXBean.getHeapMemoryUsage();
      long estimated = shallowSizeOf(all);
      if (estimated > 50 * RamUsageEstimator.ONE_MB) {
        break;
      }

      System.out.println(String.format(Locale.ROOT, "%10s\t%10s\t%10s", 
          RamUsageEstimator.humanReadableUnits(mu.getUsed()),
          RamUsageEstimator.humanReadableUnits(mu.getMax()), 
          RamUsageEstimator.humanReadableUnits(estimated)));

      // Make another batch of objects.
      Object[] seg =  new Object[10000];
      all = Arrays.copyOf(all, all.length + 1);
      all[all.length - 1] = seg;
      for (int i = 0; i < seg.length; i++) {
        seg[i] = new byte[random().nextInt(7)];
      }
    }
  } catch (OutOfMemoryError e) {
    // Release and quit.
  }
}
 
Example 37
Project: hadoop-on-lustre   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 38
Project: hadoop-on-lustre2   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 39
Project: appstatus   File: JvmPropertyProvider.java   View Source Code Vote up 5 votes
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 40
Project: cumulus   File: NamenodeJspHelper.java   View Source Code Vote up 5 votes
static String getInodeLimitText(FSNamesystem fsn) {
  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();

  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
  MemoryUsage heap = mem.getHeapMemoryUsage();
  long totalMemory = heap.getUsed();
  long maxMemory = heap.getMax();
  long commitedMemory = heap.getCommitted();
  
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();
  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalMemory * 100) / commitedMemory;
  long usedNonHeap = (totalNonHeap * 100) / commitedNonHeap;

  String str = inodes + " files and directories, " + blocks + " blocks = "
      + (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100) / maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".<br>";
  str += "Heap Memory used " + StringUtils.byteDesc(totalMemory) + " is "
      + " " + used + "% of Commited Heap Memory " 
      + StringUtils.byteDesc(commitedMemory)
      + ". Max Heap Memory is " + StringUtils.byteDesc(maxMemory) +
      ". <br>";
  str += "Non Heap Memory used " + StringUtils.byteDesc(totalNonHeap) + " is"
      + " " + usedNonHeap + "% of " + " Commited Non Heap Memory "
      + StringUtils.byteDesc(commitedNonHeap) + ". Max Non Heap Memory is "
      + StringUtils.byteDesc(maxNonHeap) + ".<br>";
  return str;
}
 
Example 41
Project: RDFS   File: JvmMetrics.java   View Source Code Vote up 5 votes
private void doMemoryUpdates() {
    MemoryMXBean memoryMXBean =
           ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap =
            memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap =
            memoryMXBean.getHeapMemoryUsage();
    metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed()/M);
    metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted()/M);
    metrics.setMetric("memHeapUsedM", memHeap.getUsed()/M);
    metrics.setMetric("memHeapCommittedM", memHeap.getCommitted()/M);
}
 
Example 42
Project: hadoop-0.20   File: JvmMetrics.java   View Source Code Vote up 5 votes
private void doMemoryUpdates() {
    MemoryMXBean memoryMXBean =
           ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap =
            memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap =
            memoryMXBean.getHeapMemoryUsage();
    metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed()/M);
    metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted()/M);
    metrics.setMetric("memHeapUsedM", memHeap.getUsed()/M);
    metrics.setMetric("memHeapCommittedM", memHeap.getCommitted()/M);
}
 
Example 43
Project: freeVM   File: ManagementFactoryTest.java   View Source Code Vote up 5 votes
public void testNewPlatformMXBeanProxy_MemoryMXBean() throws Exception {
    MemoryMXBean proxy = ManagementFactory.newPlatformMXBeanProxy(
            ManagementFactory.getPlatformMBeanServer(),
            "java.lang:type=Memory", MemoryMXBean.class);
    assertNotNull(proxy);
    MemoryMXBean mb = ManagementFactory.getMemoryMXBean();
    // RI's MemoryUsage does not appear to override equals() so we have to
    // go the long way round to check that the answers match...
    MemoryUsage mu1 = mb.getHeapMemoryUsage();
    MemoryUsage mu2 = proxy.getHeapMemoryUsage();
    assertEquals(mu1.getInit(), mu2.getInit());
    assertEquals(mu1.getMax(), mu2.getMax());

    mu1 = mb.getNonHeapMemoryUsage();
    mu2 = proxy.getNonHeapMemoryUsage();
    assertEquals(mu1.getInit(), mu2.getInit());
    assertEquals(mu1.getMax(), mu2.getMax());

    assertEquals(mb.isVerbose(), proxy.isVerbose());
    // changes made to proxy should be seen in the "real bean" and
    // vice versa
    boolean initialValue = proxy.isVerbose();
    mb.setVerbose(!initialValue);
    assertEquals(!initialValue, proxy.isVerbose());
    proxy.setVerbose(initialValue);
    assertEquals(initialValue, mb.isVerbose());
}
 
Example 44
Project: freeVM   File: ManagementFactoryTest.java   View Source Code Vote up 5 votes
public void testNewPlatformMXBeanProxy_MemoryMXBean() throws Exception {
    MemoryMXBean proxy = ManagementFactory.newPlatformMXBeanProxy(
            ManagementFactory.getPlatformMBeanServer(),
            "java.lang:type=Memory", MemoryMXBean.class);
    assertNotNull(proxy);
    MemoryMXBean mb = ManagementFactory.getMemoryMXBean();
    // RI's MemoryUsage does not appear to override equals() so we have to
    // go the long way round to check that the answers match...
    MemoryUsage mu1 = mb.getHeapMemoryUsage();
    MemoryUsage mu2 = proxy.getHeapMemoryUsage();
    assertEquals(mu1.getInit(), mu2.getInit());
    assertEquals(mu1.getMax(), mu2.getMax());

    mu1 = mb.getNonHeapMemoryUsage();
    mu2 = proxy.getNonHeapMemoryUsage();
    assertEquals(mu1.getInit(), mu2.getInit());
    assertEquals(mu1.getMax(), mu2.getMax());

    assertEquals(mb.isVerbose(), proxy.isVerbose());
    // changes made to proxy should be seen in the "real bean" and
    // vice versa
    boolean initialValue = proxy.isVerbose();
    mb.setVerbose(!initialValue);
    assertEquals(!initialValue, proxy.isVerbose());
    proxy.setVerbose(initialValue);
    assertEquals(initialValue, mb.isVerbose());
}
 
Example 45
Project: Maskana-Gestor-de-Conocimiento   File: StressRamUsageEstimator.java   View Source Code Vote up 5 votes
public void testSimpleByteArrays() {
  MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

  Object [][] all = new Object [0][];
  try {
    while (true) {
      // Check the current memory consumption and provide the estimate.
      causeGc();
      MemoryUsage mu = memoryMXBean.getHeapMemoryUsage();
      long estimated = shallowSizeOf(all);
      if (estimated > 50 * RamUsageEstimator.ONE_MB) {
        break;
      }

      System.out.println(String.format(Locale.ROOT, "%10s\t%10s\t%10s", 
          RamUsageEstimator.humanReadableUnits(mu.getUsed()),
          RamUsageEstimator.humanReadableUnits(mu.getMax()), 
          RamUsageEstimator.humanReadableUnits(estimated)));

      // Make another batch of objects.
      Object[] seg =  new Object[10000];
      all = Arrays.copyOf(all, all.length + 1);
      all[all.length - 1] = seg;
      for (int i = 0; i < seg.length; i++) {
        seg[i] = new byte[random().nextInt(7)];
      }
    }
  } catch (OutOfMemoryError e) {
    // Release and quit.
  }
}
 
Example 46
Project: RemInD   File: ServerStatusRestService.java   View Source Code Vote up 5 votes
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/status")
public ServerStatusDto getServerStatus()
{
	ServerStatusDto statusDto = new ServerStatusDto();		
	
	RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
	
	statusDto.setVmName(runtimeBean.getVmName());
	statusDto.setVmVendor(runtimeBean.getVmVendor());
	statusDto.setVmVersion(runtimeBean.getVmVersion());
	statusDto.setStartTime(new Date(runtimeBean.getStartTime()));
	statusDto.setUptime(runtimeBean.getUptime());

	MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
	MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();

	statusDto.setHeapInit(heapUsage.getInit());
	statusDto.setHeapUsed(heapUsage.getUsed());
	statusDto.setHeapMax(heapUsage.getMax());
	
	ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
	statusDto.setThreadCount(threadBean.getThreadCount());
	statusDto.setThreadPeakCount(threadBean.getPeakThreadCount());

	OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();
	statusDto.setSystemArch(operatingSystemBean.getArch());
	statusDto.setSystemName(operatingSystemBean.getName());
	statusDto.setSystemLoad(operatingSystemBean.getSystemLoadAverage());
	statusDto.setAvailableProcessors(operatingSystemBean.getAvailableProcessors());
	
	return statusDto;
}
 
Example 47
Project: hortonworks-extension   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 48
Project: hortonworks-extension   File: JvmMetrics.java   View Source Code Vote up 5 votes
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 49
Project: hadoop-gpu   File: JvmMetrics.java   View Source Code Vote up 5 votes
private void doMemoryUpdates() {
    MemoryMXBean memoryMXBean =
           ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap =
            memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap =
            memoryMXBean.getHeapMemoryUsage();
    metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed()/M);
    metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted()/M);
    metrics.setMetric("memHeapUsedM", memHeap.getUsed()/M);
    metrics.setMetric("memHeapCommittedM", memHeap.getCommitted()/M);
}
 
Example 50
Project: incubator-netbeans   File: DiagnosticTask.java   View Source Code Vote up 4 votes
private String logParams() {
        StringBuilder sb = new StringBuilder(500);
        sb.append("Diagnostic information\n");
        try {
            RuntimeMXBean         rmBean     = ManagementFactory.getRuntimeMXBean();
            CompilationMXBean     cmpMBean   = ManagementFactory.getCompilationMXBean();
//            ThreadMXBean          tmBean     = ManagementFactory.getThreadMXBean();
            MemoryMXBean          memoryBean = ManagementFactory.getMemoryMXBean();
            ClassLoadingMXBean    clMBean    = ManagementFactory.getClassLoadingMXBean();

//            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
//            ObjectName hsDiag = new ObjectName("com.sun.management:name=HotSpotDiagnostic");
//            com.sun.management.OperatingSystemMXBean sunOSMBean  =
//               ManagementFactory.getSunOperatingSystemMXBean();

//            Map<String, String> props = new TreeMap<String, String>(rmBean.getSystemProperties());
//            System.out.println("System properties");
//            for (Map.Entry<String, String> entry: props.entrySet()) {
//                System.out.println("Property: "+entry.getKey()+" Value: "+entry.getValue());
//            }
            sb.append("Input arguments:");
            for (String s: rmBean.getInputArguments()) {
                sb.append("\n\t").append(s);
            }
            
            if (cmpMBean != null) {
                sb.append("\nCompiler: "+cmpMBean.getName()).append('\n');
            }
            
            // Memory
            MemoryUsage usage = memoryBean.getHeapMemoryUsage();
            logMemoryUsage(sb, usage, "Heap memory");
            usage = memoryBean.getNonHeapMemoryUsage();
            logMemoryUsage(sb, usage, "Non heap memory");
            for (GarbageCollectorMXBean gcMBean: ManagementFactory.getGarbageCollectorMXBeans()) {
                sb.append("Garbage collector: ").append(gcMBean.getName())
                        .append(" (Collections=").append(gcMBean.getCollectionCount())
                        .append(" Total time spent=").append(formatTime(gcMBean.getCollectionTime()))
                        .append(")\n");
            }
            
            // classes
            int clsLoaded;
            long clsTotal, clsUnloaded;
            clsLoaded = clMBean.getLoadedClassCount();
            clsTotal = clMBean.getTotalLoadedClassCount();
            clsUnloaded = clMBean.getUnloadedClassCount();
            sb.append("Classes: loaded=").append(clsLoaded)
                    .append(" total loaded=").append(clsTotal)
                    .append(" unloaded ").append(clsUnloaded).append('\n');

//        } catch (MalformedObjectNameException ex) {
//            Logger.getLogger("global").log(Level.WARNING, null, ex);
        } catch (NullPointerException ex) {
            LOG.log(Level.WARNING, null, ex);
        }
        return sb.toString();
    }
 
Example 51
Project: lams   File: RuntimeStatsServlet.java   View Source Code Vote up 4 votes
private static String getLongStats() {
StringBuilder resp = new StringBuilder();

MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
    resp.append("jvmRoute: ").append(SessionManager.getJvmRoute()).append("\n");

    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = memoryBean.getHeapMemoryUsage();
    resp.append("Heap memory MB [init/used/committed/max]: ")
	    .append(RuntimeStatsServlet.toMB(memoryUsage.getInit())).append("/")
	    .append(RuntimeStatsServlet.toMB(memoryUsage.getUsed())).append("/")
	    .append(RuntimeStatsServlet.toMB(memoryUsage.getCommitted())).append("/")
	    .append(RuntimeStatsServlet.toMB(memoryUsage.getMax())).append("\n");

    memoryUsage = memoryBean.getNonHeapMemoryUsage();
    resp.append("Non-heap memory MB [init/used/committed/max]: ")
	    .append(RuntimeStatsServlet.toMB(memoryUsage.getInit())).append("/")
	    .append(RuntimeStatsServlet.toMB(memoryUsage.getUsed())).append("/")
	    .append(RuntimeStatsServlet.toMB(memoryUsage.getCommitted())).append("/")
	    .append(RuntimeStatsServlet.toMB(memoryUsage.getMax())).append("\n");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    resp.append("JVM threads [daemon/total/peak]: ").append(threadBean.getDaemonThreadCount()).append("/")
	    .append(threadBean.getThreadCount()).append("/").append(threadBean.getPeakThreadCount())
	    .append("\n");

    /*
     * Connector statistics do not seem to be present for WF 8.
     * They should be available in WF 9+ (WFLY-4420).
     * ObjectName connectorName = new ObjectName("jboss.as.expr:subsystem=io,worker=default");
     * Integer busyThreads = (Integer) server.getAttribute(connectorName, "ioThreads");
     * Integer maxThreads = (Integer) server.getAttribute(connectorName, "taskMaxThreads");
     * resp.append("IO threads [io/task max]: "
     * ).append(busyThreads).append("/").append(maxThreads).append("\n");
     */

    resp.append("Active sessions : ").append(SessionManager.getSessionCount()).append("\n");

    ObjectName dataSourceName = new ObjectName(
	    "jboss.as.expr:subsystem=datasources,data-source=lams-ds,statistics=pool");
    String inUseConnections = (String) server.getAttribute(dataSourceName, "InUseCount");
    String activeConnections = (String) server.getAttribute(dataSourceName, "ActiveCount");
    String availConnections = (String) server.getAttribute(dataSourceName, "AvailableCount");
    resp.append("Connections [in use/active/total]: ").append(inUseConnections).append("/")
	    .append(activeConnections).append("/").append(availConnections).append("\n");
} catch (Exception e) {
    RuntimeStatsServlet.log.error("Error while getting long runtime stats", e);
}

return resp.toString();
   }
 
Example 52
Project: feeyo-redisproxy   File: JavaUtils.java   View Source Code Vote up 4 votes
public static Double getMemUsage() {
	if ( isLinux() ) {
		try {
			Double value;
			String pid = JavaUtils.process_pid();
			String command = String.format("top -b -n 1 -p %s | grep -w %s", pid, pid);
			String output = SystemOperation.exec(command);

			int m = 0;
			String[] strArray = output.split(" ");
			for (int i = 0; i < strArray.length; i++) {
				String info = strArray[i];
				if (info.trim().length() == 0) {
					continue;
				}
				if (m == 5) {
					// memory
					String unit = info.substring(info.length() - 1);

					if (unit.equalsIgnoreCase("g")) {
						value = Double.parseDouble(info.substring(0, info.length() - 1));
						value *= 1000000000;
					} else if (unit.equalsIgnoreCase("m")) {
						value = Double.parseDouble(info.substring(0, info.length() - 1));
						value *= 1000000;
					} else if (unit.equalsIgnoreCase("t")) {
						value = Double.parseDouble(info.substring(0, info.length() - 1));
						value *= 1000000000000l;
					} else {
						value = Double.parseDouble(info);
					}

					// LOG.info("!!!! Get Memory Size:{}, info:{}", value,
					// info);
					return value;
				}
				if (m == 8) {
					// cpu usage
				}
				if (m == 9) {
					// memory ratio
				}
				m++;
			}
		} catch (Exception e) {
			LOGGER.warn("Failed to get memory usage", e);
		}
	}

	// this will be incorrect
	MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
	MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();

	return (double) memoryUsage.getUsed();
}
 
Example 53
Project: gemfirexd-oss   File: GemFireXDDataExtractorImpl.java   View Source Code Vote up 4 votes
protected int getNumberOfThreads (List<ServerInfo> serverInfoList, List<DiskStoreImpl> diskStores) {
  /****
   * As we extract one diskstore at a time for a given server. 
   * Here the logic is we find the largest disk-store and use its size as a basis for worst case heap memory required 
   * for salvaging a server at a given time.
   * This helps in determining how may servers can we salvage in parallel for given heap memory.
   * This is a very conservative estimate. 
   */
  long maxDiskStoreSizeOnDisk = 0;
  int maxNumberOfServersInParallel = 1;
  final double mbDiv = Math.pow(1024, 2);

  for (ServerInfo serverInfo : serverInfoList) {
    long maxDiskStoreSizeForServer = ExtractorUtils.getMaxDiskStoreSizeForServer(serverInfo, diskStores);
    if (maxDiskStoreSizeOnDisk < maxDiskStoreSizeForServer) {
      maxDiskStoreSizeOnDisk = maxDiskStoreSizeForServer;
    }
  }

  logInfo("Maximum disk-store size on disk " + maxDiskStoreSizeOnDisk/mbDiv + " MB");
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage heapMemUsage = memBean.getHeapMemoryUsage();
  long usedMemory = heapMemUsage.getUsed();
  long committedMemory = heapMemUsage.getCommitted();

  //For safety using the committedMemory for calculation, as it is the memory that is guaranteed to be available for the VM. 
  long availableMemory = (committedMemory - usedMemory);
  logInfo("Available memory : " + availableMemory/mbDiv + " MB");

  double maxMemoryPerServer = (2.2)*maxDiskStoreSizeOnDisk;

  //Setting the lower limit
  if (maxMemoryPerServer < 1) {
    maxMemoryPerServer = 1;
  }

  logInfo("Estimated memory needed per server : " + maxMemoryPerServer/mbDiv + " MB");

  if (availableMemory < maxMemoryPerServer) {
    logWarning("Not enough memory to extract the server, extractor could possibly run out of memory");
  }

  maxNumberOfServersInParallel =  (int) (availableMemory/maxMemoryPerServer);

  if (maxNumberOfServersInParallel < 1) {
    maxNumberOfServersInParallel = 1;
  }

  logInfo("Recommended number of threads to extract server(s) in parallel : " + maxNumberOfServersInParallel);
  return maxNumberOfServersInParallel;
}
 
Example 54
Project: gemfirexd-oss   File: ExtractorUtils.java   View Source Code Vote up 4 votes
public static int getNumberOfThreads (List<ServerInfo> serverInfoList, List<DiskStoreImpl> diskStores) {
  /****
   * As we extract one diskstore at a time for a given server. 
   * Here the logic is we find the largest disk-store and use its size as a basis for worst case heap memory required 
   * for salvaging a server at a given time.
   * This helps in determining how may servers can we salvage in parallel for given heap memory.
   * This is a very conservative estimate. 
   */
  long maxDiskStoreSizeOnDisk = 0;
  int maxNumberOfServersInParallel = 1;
  final double mbDiv = Math.pow(1024, 2);

  for (ServerInfo serverInfo : serverInfoList) {
    long maxDiskStoreSizeForServer = ExtractorUtils.getMaxDiskStoreSizeForServer(serverInfo, diskStores);
    if (maxDiskStoreSizeOnDisk < maxDiskStoreSizeForServer) {
      maxDiskStoreSizeOnDisk = maxDiskStoreSizeForServer;
    }
  }

  GemFireXDDataExtractorImpl.logInfo("Maximum disk-store size on disk " + maxDiskStoreSizeOnDisk/mbDiv + " MB");
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage heapMemUsage = memBean.getHeapMemoryUsage();
  long usedMemory = heapMemUsage.getUsed();
  long committedMemory = heapMemUsage.getCommitted();

  //For safety using the committedMemory for calculation, as it is the memory that is guaranteed to be available for the VM. 
  long availableMemory = (committedMemory - usedMemory);
  GemFireXDDataExtractorImpl.logInfo("Available memory : " + availableMemory/mbDiv + " MB");

  double maxMemoryPerServer = (1.2)*maxDiskStoreSizeOnDisk;

  //Setting the lower limit
  if (maxMemoryPerServer < 1) {
    maxMemoryPerServer = 1;
  }

  GemFireXDDataExtractorImpl.logInfo("Estimated memory needed per server : " + maxMemoryPerServer/mbDiv + " MB");

  if (availableMemory < maxMemoryPerServer) {
    GemFireXDDataExtractorImpl.logWarning("Not enough memory to extract the server, extractor could possibly run out of memory");
  }

  maxNumberOfServersInParallel =  (int) (availableMemory/maxMemoryPerServer);

  if (maxNumberOfServersInParallel < 1) {
    maxNumberOfServersInParallel = 1;
  }

  GemFireXDDataExtractorImpl.logInfo("Recommended number of threads to extract server(s) in parallel : " + maxNumberOfServersInParallel);
  return maxNumberOfServersInParallel;
}
 
Example 55
Project: mdw   File: SystemUtil.java   View Source Code Vote up 4 votes
public synchronized String getMemoryInfo() {
    String info = "";
    StringBuffer output = new StringBuffer();

    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();

    MemoryUsage heapMemUsage = memBean.getHeapMemoryUsage();
    output.append("Heap Memory:\n------------\n");
    output.append(memoryUsage(heapMemUsage, 0));

    output.append("\n");

    MemoryUsage nonHeapMemUsage = memBean.getNonHeapMemoryUsage();
    output.append("Non-Heap Memory:\n----------------\n");
    output.append(memoryUsage(nonHeapMemUsage, 0));

    output.append("\n");

    output.append("Objects Pending Finalization: "
            + memBean.getObjectPendingFinalizationCount() + "\n\n");

    output.append("Memory Pools:\n-------------\n");
    List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean memoryPoolBean : memoryPoolBeans) {
        output.append(memoryPoolBean.getName() + " ");
        output.append("(type=" + memoryPoolBean.getType() + "):\n");

        if (memoryPoolBean.isUsageThresholdSupported()) {
            output.append("\tUsage Threshold:" + memoryPoolBean.getUsageThreshold() + " ("
                    + (memoryPoolBean.getUsageThreshold() >> 10) + "K)\n");
            output.append("\tUsage Threshold Count:" + memoryPoolBean.getUsageThresholdCount()
                    + " (" + (memoryPoolBean.getUsageThresholdCount() >> 10) + "K)\n");
            output.append("\tUsage Threshold Exceeded: "
                    + memoryPoolBean.isUsageThresholdExceeded() + "\n");
        }

        if (memoryPoolBean.isCollectionUsageThresholdSupported()) {
            output.append("\tCollection Usage Threshold: "
                    + memoryPoolBean.getCollectionUsageThreshold() + " ("
                    + (memoryPoolBean.getCollectionUsageThreshold() >> 10) + "K)\n");
            output.append("\tCollection Usage Threshold Count: "
                    + memoryPoolBean.getCollectionUsageThresholdCount() + " ("
                    + (memoryPoolBean.getCollectionUsageThresholdCount() >> 10) + "K)\n");
            output.append("\tCollection Usage Threshold Exceeded: "
                    + memoryPoolBean.isCollectionUsageThresholdExceeded() + "\n");
        }

        if (memoryPoolBean.isUsageThresholdSupported() && memoryPoolBean.getUsage() != null) {
            output.append("\n\tUsage:\n\t------\n").append(
                    memoryUsage(memoryPoolBean.getUsage(), 1));
        }
        if (memoryPoolBean.isCollectionUsageThresholdSupported()
                && memoryPoolBean.getCollectionUsage() != null) {
            output.append("\n\tCollection Usage:\n\t-----------------\n").append(
                    memoryUsage(memoryPoolBean.getCollectionUsage(), 1));
        }
        if (memoryPoolBean.getPeakUsage() != null) {
            output.append("\n\tPeak Usage:\n\t-----------\n").append(
                    memoryUsage(memoryPoolBean.getPeakUsage(), 1));
        }

        String[] memoryManagerNames = memoryPoolBean.getMemoryManagerNames();
        if (memoryManagerNames != null) {
            output.append("\n\tMemory Manager Names: ");
            for (String memoryManagerName : memoryManagerNames)
                output.append(memoryManagerName + " ");
            output.append("\n");
        }

        output.append("\n");
    }

    info = output.toString();
    System.out.println(info);
    return info;
}
 
Example 56
Project: hadoop-2.6.0-cdh5.4.3   File: NamenodeJspHelper.java   View Source Code Vote up 4 votes
static String getInodeLimitText(FSNamesystem fsn) {
  if (fsn == null) {
    return "";
  }

  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();

  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
  MemoryUsage heap = mem.getHeapMemoryUsage();
  long totalMemory = heap.getUsed();
  long maxMemory = heap.getMax();
  long commitedMemory = heap.getCommitted();
  
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();
  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalMemory * 100) / commitedMemory;
  long usedNonHeap = (totalNonHeap * 100) / commitedNonHeap;

  String str = "<div>" + inodes + " files and directories, " + blocks + " blocks = "
      + (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100) / maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".</div>";
  str += "<div>Heap Memory used " + StringUtils.byteDesc(totalMemory) + " is "
      + " " + used + "% of Commited Heap Memory "
      + StringUtils.byteDesc(commitedMemory)
      + ". Max Heap Memory is " + StringUtils.byteDesc(maxMemory) +
      ". </div>";
  str += "<div>Non Heap Memory used " + StringUtils.byteDesc(totalNonHeap) + " is"
      + " " + usedNonHeap + "% of " + " Commited Non Heap Memory "
      + StringUtils.byteDesc(commitedNonHeap) + ". Max Non Heap Memory is "
      + StringUtils.byteDesc(maxNonHeap) + ".</div>";
  return str;
}
 
Example 57
Project: swing   File: InfoDialog.java   View Source Code Vote up 4 votes
private String getMemoryUsage() {
    MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = mbean.getHeapMemoryUsage();
    long usedMemory = (memoryUsage.getUsed() / 1024) / 1000;
    return NumberFormat.getInstance().format(usedMemory) + "MB";
}
 
Example 58
Project: purej-vminspect   File: SystemData.java   View Source Code Vote up 4 votes
/**
 * Creates a new instance of this class.
 */
public SystemData() {
  // Store runtime-infos:
  _rtInfo = System.getProperty("java.runtime.name") + ", " + System.getProperty("java.runtime.version");
  _rtb = ManagementFactory.getRuntimeMXBean();

  // Store thread-infos:
  ThreadMXBean tb = ManagementFactory.getThreadMXBean();
  _threadCurrentCount = tb.getThreadCount();

  // Get class-loader stuff:
  ClassLoadingMXBean clb = ManagementFactory.getClassLoadingMXBean();
  _clLoadedClassCount = clb.getLoadedClassCount();
  _clTotalLoadedClassCount = clb.getTotalLoadedClassCount();

  // Build gc collection time:
  long tmpGcCollectionCount = 0;
  long tmpGcCollectionTimeMillis = 0;
  for (GarbageCollectorMXBean garbageCollector : ManagementFactory.getGarbageCollectorMXBeans()) {
    tmpGcCollectionCount += garbageCollector.getCollectionCount();
    tmpGcCollectionTimeMillis += garbageCollector.getCollectionTime();
  }
  _gcCollectionCount = tmpGcCollectionCount;
  _gcCollectionTimeMillis = tmpGcCollectionTimeMillis;

  // Get heap / none heap memory:
  MemoryMXBean mb = ManagementFactory.getMemoryMXBean();
  _memoryHeap = new MemoryData(mb.getHeapMemoryUsage());
  _memoryNonHeap = new MemoryData(mb.getNonHeapMemoryUsage());

  // Physical / swap memory - is hidden, type is long (eg. bytes):
  _osb = ManagementFactory.getOperatingSystemMXBean();
  long memPhysTotal = getHiddenInfoLong(_osb, "getTotalPhysicalMemorySize");
  long memPhysFree = getHiddenInfoLong(_osb, "getFreePhysicalMemorySize");
  _memoryPhysical = new MemoryData(memPhysTotal != -1 ? memPhysTotal - memPhysFree : -1, -1, memPhysTotal);
  long memSwapTotal = getHiddenInfoLong(_osb, "getTotalSwapSpaceSize");
  long memSwapFree = getHiddenInfoLong(_osb, "getFreeSwapSpaceSize");
  _memorySwap = new MemoryData(memSwapTotal != -1 ? memSwapTotal - memSwapFree : -1, -1, memSwapTotal);

  // Process Cpu time is hidden - value is in nanoseconds:
  Object cpuTime = getHiddenInfo(_osb, "getProcessCpuTime");
  _processCpuTimeMillis = cpuTime != null ? ((Long) cpuTime).longValue() / 1000000 : -1;

  // Process Cpu load is hidden - value is a double between 0..1:
  Object cpuLoad = getHiddenInfo(_osb, "getProcessCpuLoad");
  double processCpuLoadPct = cpuLoad != null ? ((Double) cpuLoad).doubleValue() : -1;
  _processCpuLoadPct = processCpuLoadPct < 0 ? processCpuLoadPct : processCpuLoadPct * 100;

  // System Cpu load is hidden - value is a double between 0..1:
  Object systemLoad = getHiddenInfo(_osb, "getSystemCpuLoad");
  double systemCpuLoadPct = systemLoad != null ? ((Double) systemLoad).doubleValue() : -1;
  _systemCpuLoadPct = systemCpuLoadPct < 0 ? systemCpuLoadPct : systemCpuLoadPct * 100;

  // Open/Max file descriptor count:
  _openFileDescriptorCount = getHiddenInfoLong(_osb, "getOpenFileDescriptorCount");
  _maxFileDescriptorCount = getHiddenInfoLong(_osb, "getMaxFileDescriptorCount");
}
 
Example 59
Project: gemfirexd-oss   File: GemFireXDDataExtractorImpl.java   View Source Code Vote up 4 votes
protected int getNumberOfThreads (List<ServerInfo> serverInfoList, List<DiskStoreImpl> diskStores) {
  /****
   * As we extract one diskstore at a time for a given server. 
   * Here the logic is we find the largest disk-store and use its size as a basis for worst case heap memory required 
   * for salvaging a server at a given time.
   * This helps in determining how may servers can we salvage in parallel for given heap memory.
   * This is a very conservative estimate. 
   */
  long maxDiskStoreSizeOnDisk = 0;
  int maxNumberOfServersInParallel = 1;
  final double mbDiv = Math.pow(1024, 2);

  for (ServerInfo serverInfo : serverInfoList) {
    long maxDiskStoreSizeForServer = ExtractorUtils.getMaxDiskStoreSizeForServer(serverInfo, diskStores);
    if (maxDiskStoreSizeOnDisk < maxDiskStoreSizeForServer) {
      maxDiskStoreSizeOnDisk = maxDiskStoreSizeForServer;
    }
  }

  logInfo("Maximum disk-store size on disk " + maxDiskStoreSizeOnDisk/mbDiv + " MB");
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage heapMemUsage = memBean.getHeapMemoryUsage();
  long usedMemory = heapMemUsage.getUsed();
  long committedMemory = heapMemUsage.getCommitted();

  //For safety using the committedMemory for calculation, as it is the memory that is guaranteed to be available for the VM. 
  long availableMemory = (committedMemory - usedMemory);
  logInfo("Available memory : " + availableMemory/mbDiv + " MB");

  double maxMemoryPerServer = (2.2)*maxDiskStoreSizeOnDisk;

  //Setting the lower limit
  if (maxMemoryPerServer < 1) {
    maxMemoryPerServer = 1;
  }

  logInfo("Estimated memory needed per server : " + maxMemoryPerServer/mbDiv + " MB");

  if (availableMemory < maxMemoryPerServer) {
    logWarning("Not enough memory to extract the server, extractor could possibly run out of memory");
  }

  maxNumberOfServersInParallel =  (int) (availableMemory/maxMemoryPerServer);

  if (maxNumberOfServersInParallel < 1) {
    maxNumberOfServersInParallel = 1;
  }

  logInfo("Recommended number of threads to extract server(s) in parallel : " + maxNumberOfServersInParallel);
  return maxNumberOfServersInParallel;
}
 
Example 60
Project: gemfirexd-oss   File: ExtractorUtils.java   View Source Code Vote up 4 votes
public static int getNumberOfThreads (List<ServerInfo> serverInfoList, List<DiskStoreImpl> diskStores) {
  /****
   * As we extract one diskstore at a time for a given server. 
   * Here the logic is we find the largest disk-store and use its size as a basis for worst case heap memory required 
   * for salvaging a server at a given time.
   * This helps in determining how may servers can we salvage in parallel for given heap memory.
   * This is a very conservative estimate. 
   */
  long maxDiskStoreSizeOnDisk = 0;
  int maxNumberOfServersInParallel = 1;
  final double mbDiv = Math.pow(1024, 2);

  for (ServerInfo serverInfo : serverInfoList) {
    long maxDiskStoreSizeForServer = ExtractorUtils.getMaxDiskStoreSizeForServer(serverInfo, diskStores);
    if (maxDiskStoreSizeOnDisk < maxDiskStoreSizeForServer) {
      maxDiskStoreSizeOnDisk = maxDiskStoreSizeForServer;
    }
  }

  GemFireXDDataExtractorImpl.logInfo("Maximum disk-store size on disk " + maxDiskStoreSizeOnDisk/mbDiv + " MB");
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage heapMemUsage = memBean.getHeapMemoryUsage();
  long usedMemory = heapMemUsage.getUsed();
  long committedMemory = heapMemUsage.getCommitted();

  //For safety using the committedMemory for calculation, as it is the memory that is guaranteed to be available for the VM. 
  long availableMemory = (committedMemory - usedMemory);
  GemFireXDDataExtractorImpl.logInfo("Available memory : " + availableMemory/mbDiv + " MB");

  double maxMemoryPerServer = (1.2)*maxDiskStoreSizeOnDisk;

  //Setting the lower limit
  if (maxMemoryPerServer < 1) {
    maxMemoryPerServer = 1;
  }

  GemFireXDDataExtractorImpl.logInfo("Estimated memory needed per server : " + maxMemoryPerServer/mbDiv + " MB");

  if (availableMemory < maxMemoryPerServer) {
    GemFireXDDataExtractorImpl.logWarning("Not enough memory to extract the server, extractor could possibly run out of memory");
  }

  maxNumberOfServersInParallel =  (int) (availableMemory/maxMemoryPerServer);

  if (maxNumberOfServersInParallel < 1) {
    maxNumberOfServersInParallel = 1;
  }

  GemFireXDDataExtractorImpl.logInfo("Recommended number of threads to extract server(s) in parallel : " + maxNumberOfServersInParallel);
  return maxNumberOfServersInParallel;
}
 
Example 61
Project: hadoop-plus   File: NamenodeJspHelper.java   View Source Code Vote up 4 votes
static String getInodeLimitText(FSNamesystem fsn) {
  if (fsn == null) {
    return "";
  }

  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();

  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
  MemoryUsage heap = mem.getHeapMemoryUsage();
  long totalMemory = heap.getUsed();
  long maxMemory = heap.getMax();
  long commitedMemory = heap.getCommitted();
  
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();
  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalMemory * 100) / commitedMemory;
  long usedNonHeap = (totalNonHeap * 100) / commitedNonHeap;

  String str = "<div>" + inodes + " files and directories, " + blocks + " blocks = "
      + (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100) / maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".</div>";
  str += "<div>Heap Memory used " + StringUtils.byteDesc(totalMemory) + " is "
      + " " + used + "% of Commited Heap Memory "
      + StringUtils.byteDesc(commitedMemory)
      + ". Max Heap Memory is " + StringUtils.byteDesc(maxMemory) +
      ". </div>";
  str += "<div>Non Heap Memory used " + StringUtils.byteDesc(totalNonHeap) + " is"
      + " " + usedNonHeap + "% of " + " Commited Non Heap Memory "
      + StringUtils.byteDesc(commitedNonHeap) + ". Max Non Heap Memory is "
      + StringUtils.byteDesc(maxNonHeap) + ".</div>";
  return str;
}
 
Example 62
Project: artifactory   File: SystemInfoPage.java   View Source Code Vote up 4 votes
/**
 * Return a formatted string of the system info to display
 *
 * @return
 */
private String collectSystemInfo() {
    StringBuilder infoBuilder = new StringBuilder();

    StorageProperties storageProperties = ContextHelper.get().beanForType(StorageProperties.class);
    infoBuilder.append("Storage Info:").append("\n");
    addInfo(infoBuilder, "Database Type", storageProperties.getDbType().toString());
    BinaryProviderType binariesStorageType = storageProperties.getBinariesStorageType();
    addInfo(infoBuilder, "Storage Type", binariesStorageType.toString());
    if (BinaryProviderType.S3 == binariesStorageType) {
        // S3 properties
        addInfo(infoBuilder, "s3.bucket.name", storageProperties.getS3BucketName());
        addInfo(infoBuilder, "s3.bucket.path", storageProperties.getS3BucketPath());
        addInfo(infoBuilder, "s3.endpoint", storageProperties.getS3Entpoint());
        // Retry properties
        addInfo(infoBuilder, "retry.max.retries.number", Integer.toString(
                storageProperties.getMaxRetriesNumber()));
        addInfo(infoBuilder, "retry.delay.between.retries", Integer.toString(
                storageProperties.getDelayBetweenRetries()));
        // Eventually persisted properties
        addInfo(infoBuilder, "eventually.persisted.max.number.of.threads", Integer.toString(
                storageProperties.getEventuallyPersistedMaxNumberOfThread()));
        addInfo(infoBuilder, "eventually.persisted.timeout", Integer.toString(
                storageProperties.getEventuallyPersistedTimeOut()));
        addInfo(infoBuilder, "eventually.dispatcher.sleep.time", Long.toString(
                storageProperties.getEventuallyPersistedDispatcherSleepTime()));
    }

    infoBuilder.append("\n").append("System Properties:").append("\n");
    Properties properties = System.getProperties();
    //// add Artifactory version to the properties, will be alphabetically sorted later.
    properties.setProperty(ConstantValues.artifactoryVersion.getPropertyName(),
            ConstantValues.artifactoryVersion.getString());
    AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class);
    addInfo(infoBuilder, "artifactory.running.mode", addonsManager.getArtifactoryRunningMode().name());
    addInfo(infoBuilder, "artifactory.running.state", ContextHelper.get().isOffline() ? "Offline" : "Online");
    addFromProperties(infoBuilder, properties);
    addHaProperties(infoBuilder);
    infoBuilder.append("\n").append("General JVM Info:").append("\n");
    OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean();
    addInfo(infoBuilder, "Available Processors", Integer.toString(systemBean.getAvailableProcessors()));

    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();

    addInfo(infoBuilder, "Heap Memory Usage-Committed", Long.toString(heapMemoryUsage.getCommitted()));
    addInfo(infoBuilder, "Heap Memory Usage-Init", Long.toString(heapMemoryUsage.getInit()));
    addInfo(infoBuilder, "Heap Memory Usage-Max", Long.toString(heapMemoryUsage.getMax()));
    addInfo(infoBuilder, "Heap Memory Usage-Used", Long.toString(heapMemoryUsage.getUsed()));

    MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage();
    addInfo(infoBuilder, "Non-Heap Memory Usage-Committed", Long.toString(nonHeapMemoryUsage.getCommitted()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Init", Long.toString(nonHeapMemoryUsage.getInit()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Max", Long.toString(nonHeapMemoryUsage.getMax()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Used", Long.toString(nonHeapMemoryUsage.getUsed()));

    RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
    StringBuilder vmArgumentBuilder = new StringBuilder();
    List<String> vmArguments = RuntimemxBean.getInputArguments();
    if (vmArguments != null) {
        for (String vmArgument : vmArguments) {
            if (InfoWriter.shouldMaskValue(vmArgument)) {
                vmArgument = Strings.maskKeyValue(vmArgument);
            }
            vmArgumentBuilder.append(vmArgument);
            if (vmArguments.indexOf(vmArgument) != (vmArguments.size() - 1)) {
                vmArgumentBuilder.append("\n");
            }
        }
    }

    infoBuilder.append("\nJVM Arguments:\n").append(vmArgumentBuilder.toString());

    return StringUtils.removeEnd(infoBuilder.toString(), "\n");
}
 
Example 63
Project: CliRel   File: MemoryUtils.java   View Source Code Vote up 4 votes
public static double getHeapMemoryUsed() {
	MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
	MemoryUsage usage = bean.getHeapMemoryUsage();
	long bytes = usage.getUsed();
	return bytes / 1.0e6;
}
 
Example 64
Project: hops   File: NamenodeJspHelper.java   View Source Code Vote up 4 votes
static String getInodeLimitText(FSNamesystem fsn) throws IOException {
  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();

  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
  MemoryUsage heap = mem.getHeapMemoryUsage();
  long totalMemory = heap.getUsed();
  long maxMemory = heap.getMax();
  long commitedMemory = heap.getCommitted();
  
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();
  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalMemory * 100) / commitedMemory;
  long usedNonHeap = (totalNonHeap * 100) / commitedNonHeap;
  long directBuffer = sun.misc.SharedSecrets.getJavaNioAccess().getDirectBufferPool().getMemoryUsed();

  String str =
      "<div>" + inodes + " files and directories, " + blocks + " blocks = " +
          (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100) / maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".</div>";
  str +=
      "<div>Heap Memory used " + StringUtils.byteDesc(totalMemory) + " is " +
          " " + used + "% of Commited Heap Memory " +
          StringUtils.byteDesc(commitedMemory) + ". Max Heap Memory is " +
          StringUtils.byteDesc(maxMemory) +
          ". </div>";
  str += "<div>Non Heap Memory used " + StringUtils.byteDesc(totalNonHeap) +
      " is" + " " + usedNonHeap + "% of " + " Commited Non Heap Memory " +
      StringUtils.byteDesc(commitedNonHeap) + ". Max Non Heap Memory is " +
      StringUtils.byteDesc(maxNonHeap) + ".</div>";

  str += "<div>DirectBuffer Memeory used " + StringUtils.byteDesc(directBuffer)+".</div>";
  return str;
}
 
Example 65
Project: jmonitor   File: JMServer.java   View Source Code Vote up 4 votes
public static JSONObject loadMemoryInfo(String app) {
    try {
        MemoryMXBean mBean = JMConnManager.getMemoryMBean(app);
        MemoryUsage nonHeap = mBean.getNonHeapMemoryUsage();
        MemoryUsage heap = mBean.getHeapMemoryUsage();

        JSONObject map = new JSONObject(true);
        buildMemoryJSon(heap, "heap", map);
        buildMemoryJSon(nonHeap, "nonheap", map);

        JSONObject heapChild = new JSONObject();
        JSONObject nonheapChild = new JSONObject();

        JSONObject heapUsed = new JSONObject();
        JSONObject heapMax = new JSONObject();
        heapUsed.put("used", heap.getUsed());
        heapMax.put("used", heap.getCommitted());
        heapChild.put("HeapUsed", heapUsed);
        heapChild.put("HeapCommit", heapMax);

        JSONObject nonheapUsed = new JSONObject();
        JSONObject noheapMax = new JSONObject();
        nonheapUsed.put("used", nonHeap.getUsed());
        noheapMax.put("used", nonHeap.getCommitted());

        nonheapChild.put("NonheapUsed", nonheapUsed);
        nonheapChild.put("NonheapCommit", noheapMax);

        ObjectName obj = new ObjectName("java.lang:type=MemoryPool,*");
        MBeanServerConnection conn = JMConnManager.getConn(app);
        Set<ObjectInstance> MBeanset = conn.queryMBeans(obj, null);
        for (ObjectInstance objx : MBeanset) {
            String name = objx.getObjectName().getCanonicalName();
            String keyName = objx.getObjectName().getKeyProperty("name");
            MemoryPoolMXBean bean = JMConnManager.getServer(app, name, MemoryPoolMXBean.class);
            JSONObject item = toJson(bean.getUsage());
            if (JMConnManager.HEAP_ITEM.contains(keyName)) {
                heapChild.put(keyName, item);
            } else {
                nonheapChild.put(keyName, item);
            }
        }
        map.getJSONObject("heap").put("childs", heapChild);
        map.getJSONObject("nonheap").put("childs", nonheapChild);

        return map;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 66
Project: JHealthAgent   File: FullGCTriggerTest.java   View Source Code Vote up 4 votes
/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("chunk ratio: " + CHUNK_RATIO
				+ " / max no. of chunks: " + MAX_CHUNKS);
		MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

		MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
		long max = heapMemoryUsage.getMax();

		Map<Long, String> map = new TreeMap<Long, String>();

		LinkedList<Object> list = new LinkedList<Object>();

		long index = 0;
		long maxIndex = Long.MAX_VALUE;

		boolean measuring = true;

		while (true) {
			String s = concatSomeStuff();
			map.put(index++, s);
//			map.remove(index / 2);
//			map.remove(index / 3);
//			map.remove(index / 5);

			if (measuring && index % 20 == 0) {

				heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

				if (measuring && heapMemoryUsage.getUsed() > max * CHUNK_RATIO) {
					measuring = false;
					maxIndex = index;
					System.out.println("MaxIndex is: " + maxIndex);

				}
			}
			if (index > maxIndex) {
				heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

				list.addFirst(map);
				if (list.size() >= MAX_CHUNKS) {
					list.removeLast();
				}

				index = 0;
				map = new HashMap<Long, String>();
				System.out.println("Starting new map, usage: "
						+ heapMemoryUsage.getUsed() / 1024 / 1024
						+ " MB  committed:" + heapMemoryUsage.getCommitted()
						/ 1024 / 1024 + " MB  max:" + heapMemoryUsage.getMax()
						/ 1024 / 1024 + " MB");
			}
		}
	}
 
Example 67
Project: geolocator-3.0   File: MemoryUtils.java   View Source Code Vote up 4 votes
public static double getHeapMemoryUsed() {
	MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
	MemoryUsage usage = bean.getHeapMemoryUsage();
	long bytes = usage.getUsed();
	return bytes / 1.0e6;
}
 
Example 68
Project: hadoop-TCP   File: NamenodeJspHelper.java   View Source Code Vote up 4 votes
static String getInodeLimitText(FSNamesystem fsn) {
  if (fsn == null) {
    return "";
  }

  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();

  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
  MemoryUsage heap = mem.getHeapMemoryUsage();
  long totalMemory = heap.getUsed();
  long maxMemory = heap.getMax();
  long commitedMemory = heap.getCommitted();
  
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();
  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalMemory * 100) / commitedMemory;
  long usedNonHeap = (totalNonHeap * 100) / commitedNonHeap;

  String str = "<div>" + inodes + " files and directories, " + blocks + " blocks = "
      + (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100) / maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".</div>";
  str += "<div>Heap Memory used " + StringUtils.byteDesc(totalMemory) + " is "
      + " " + used + "% of Commited Heap Memory "
      + StringUtils.byteDesc(commitedMemory)
      + ". Max Heap Memory is " + StringUtils.byteDesc(maxMemory) +
      ". </div>";
  str += "<div>Non Heap Memory used " + StringUtils.byteDesc(totalNonHeap) + " is"
      + " " + usedNonHeap + "% of " + " Commited Non Heap Memory "
      + StringUtils.byteDesc(commitedNonHeap) + ". Max Non Heap Memory is "
      + StringUtils.byteDesc(maxNonHeap) + ".</div>";
  return str;
}
 
Example 69
Project: hardfs   File: NamenodeJspHelper.java   View Source Code Vote up 4 votes
static String getInodeLimitText(FSNamesystem fsn) {
  if (fsn == null) {
    return "";
  }

  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();

  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
  MemoryUsage heap = mem.getHeapMemoryUsage();
  long totalMemory = heap.getUsed();
  long maxMemory = heap.getMax();
  long commitedMemory = heap.getCommitted();
  
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();
  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalMemory * 100) / commitedMemory;
  long usedNonHeap = (totalNonHeap * 100) / commitedNonHeap;

  String str = "<div>" + inodes + " files and directories, " + blocks + " blocks = "
      + (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100) / maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".</div>";
  str += "<div>Heap Memory used " + StringUtils.byteDesc(totalMemory) + " is "
      + " " + used + "% of Commited Heap Memory "
      + StringUtils.byteDesc(commitedMemory)
      + ". Max Heap Memory is " + StringUtils.byteDesc(maxMemory) +
      ". </div>";
  str += "<div>Non Heap Memory used " + StringUtils.byteDesc(totalNonHeap) + " is"
      + " " + usedNonHeap + "% of " + " Commited Non Heap Memory "
      + StringUtils.byteDesc(commitedNonHeap) + ". Max Non Heap Memory is "
      + StringUtils.byteDesc(maxNonHeap) + ".</div>";
  return str;
}
 
Example 70
Project: bazel   File: InfoItem.java   View Source Code Vote up 4 votes
private static MemoryUsage getMemoryUsage() {
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  return memBean.getHeapMemoryUsage();
}
 
Example 71
Project: hadoop-on-lustre2   File: NamenodeJspHelper.java   View Source Code Vote up 4 votes
static String getInodeLimitText(FSNamesystem fsn) {
  if (fsn == null) {
    return "";
  }

  long inodes = fsn.dir.totalInodes();
  long blocks = fsn.getBlocksTotal();
  long maxobjects = fsn.getMaxObjects();

  MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
  MemoryUsage heap = mem.getHeapMemoryUsage();
  long totalMemory = heap.getUsed();
  long maxMemory = heap.getMax();
  long commitedMemory = heap.getCommitted();
  
  MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();
  long totalNonHeap = nonHeap.getUsed();
  long maxNonHeap = nonHeap.getMax();
  long commitedNonHeap = nonHeap.getCommitted();

  long used = (totalMemory * 100) / commitedMemory;
  long usedNonHeap = (totalNonHeap * 100) / commitedNonHeap;

  String str = "<div>" + inodes + " files and directories, " + blocks + " blocks = "
      + (inodes + blocks) + " total";
  if (maxobjects != 0) {
    long pct = ((inodes + blocks) * 100) / maxobjects;
    str += " / " + maxobjects + " (" + pct + "%)";
  }
  str += ".</div>";
  str += "<div>Heap Memory used " + StringUtils.byteDesc(totalMemory) + " is "
      + " " + used + "% of Commited Heap Memory "
      + StringUtils.byteDesc(commitedMemory)
      + ". Max Heap Memory is " + StringUtils.byteDesc(maxMemory) +
      ". </div>";
  str += "<div>Non Heap Memory used " + StringUtils.byteDesc(totalNonHeap) + " is"
      + " " + usedNonHeap + "% of " + " Commited Non Heap Memory "
      + StringUtils.byteDesc(commitedNonHeap) + ". Max Non Heap Memory is "
      + StringUtils.byteDesc(maxNonHeap) + ".</div>";
  return str;
}
 
Example 72
Project: common_gui_tools   File: SystemInformation.java   View Source Code Vote up 4 votes
/**
 * 虚拟机运行情况.
 */
private String getRunningStatus() {
    StringBuilder sb = new StringBuilder();

    // 虚拟机开始及总运行时间
    RuntimeMXBean runBean = ManagementFactory.getRuntimeMXBean();
    sb.append("\n").append(GuiUtils.getFillUpString("Current Time", 32)).append(new Date());
    sb.append("\n").append(GuiUtils.getFillUpString("Start Time", 32)).append(new Date(runBean.getStartTime()));
    sb.append("\n").append(GuiUtils.getFillUpString("Run Time", 32))
            .append(GuiUtils.getCountTime(runBean.getUptime()));

    sb.append("\n");
    // 操作系统可用处理器数目
    OperatingSystemMXBean operateBean = ManagementFactory.getOperatingSystemMXBean();
    sb.append("\n").append(GuiUtils.getFillUpString("System Processors", 32))
            .append(operateBean.getAvailableProcessors());

    // 内存使用情况
    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMem = memBean.getHeapMemoryUsage();
    MemoryUsage nonHeapMem = memBean.getNonHeapMemoryUsage();

    sb.append("\n");
    sb.append("\n").append(GuiUtils.getFillUpString("Heap Used", 32)).append(getMemoey(heapMem.getUsed()));
    sb.append("\n").append(GuiUtils.getFillUpString("Heap Committed", 32))
            .append(getMemoey(heapMem.getCommitted()));
    sb.append("\n").append(GuiUtils.getFillUpString("Heap Init", 32)).append(getMemoey(heapMem.getInit()));
    sb.append("\n").append(GuiUtils.getFillUpString("Heap Max", 32)).append(getMemoey(heapMem.getMax()));
    sb.append("\n");
    sb.append("\n").append(GuiUtils.getFillUpString("NonHeap Used", 32)).append(getMemoey(nonHeapMem.getUsed()));
    sb.append("\n").append(GuiUtils.getFillUpString("NonHeap Committed", 32))
            .append(getMemoey(nonHeapMem.getCommitted()));
    sb.append("\n").append(GuiUtils.getFillUpString("NonHeap Init", 32)).append(getMemoey(nonHeapMem.getInit()));
    sb.append("\n").append(GuiUtils.getFillUpString("NonHeap Max", 32)).append(getMemoey(nonHeapMem.getMax()));

    sb.append("\n");
    Runtime curRuntime = Runtime.getRuntime();
    sb.append("\n").append(GuiUtils.getFillUpString("Free Memory", 32))
            .append(getMemoey(curRuntime.freeMemory()));
    sb.append("\n").append(GuiUtils.getFillUpString("Total Memory", 32))
            .append(getMemoey(curRuntime.totalMemory()));
    sb.append("\n").append(GuiUtils.getFillUpString("Max Memory", 32)).append(getMemoey(curRuntime.maxMemory()));

    // 当前运行线程
    sb.append("\n");
    sb.append("\n").append(GuiUtils.getFillUpString("  Thread Name", 32)).append("Thread ID");
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long[] threads = threadBean.getAllThreadIds();
    ThreadInfo[] threadInfos = threadBean.getThreadInfo(threads);
    for (int i = threadInfos.length - 1; i > -1; i--) {
        sb.append("\n").append(GuiUtils.getFillUpString(threadInfos[i].getThreadName(), 32))
                .append(threadInfos[i].getThreadId());
    }
    return sb.toString();
}
 
Example 73
Project: jstorm   File: JStormUtils.java   View Source Code Vote up 4 votes
public static Double getMemUsage() {
    if (OSInfo.isLinux()) {
        try {
            Double value;
            String pid = JStormUtils.process_pid();
            String command = String.format("top -b -n 1 -p %s | grep -w %s", pid, pid);
            String output = SystemOperation.exec(command);

            int m = 0;
            String[] strArray = output.split(" ");
            for (int i = 0; i < strArray.length; i++) {
                String info = strArray[i];
                if (info.trim().length() == 0) {
                    continue;
                }
                if (m == 5) {
                    // memory
                    String unit = info.substring(info.length() - 1);

                    if (unit.equalsIgnoreCase("g")) {
                        value = Double.parseDouble(info.substring(0, info.length() - 1));
                        value *= 1000000000;
                    } else if (unit.equalsIgnoreCase("m")) {
                        value = Double.parseDouble(info.substring(0, info.length() - 1));
                        value *= 1000000;
                    } else if (unit.equalsIgnoreCase("t")) {
                        value = Double.parseDouble(info.substring(0, info.length() - 1));
                        value *= 1000000000000l;
                    } else {
                        value = Double.parseDouble(info);
                    }

                    //LOG.info("!!!! Get Memory Size:{}, info:{}", value, info);
                    return value;
                }
                if (m == 8) {
                    // cpu usage
                }
                if (m == 9) {
                    // memory ratio
                }
                m++;
            }
        } catch (Exception e) {
            LOG.warn("Failed to get memory usage", e);
        }
    }

    // this will be incorrect
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();

    return (double) memoryUsage.getUsed();
}
 
Example 74
Project: jstorm   File: JStormUtils.java   View Source Code Vote up 4 votes
public static double getJVMHeapMemory() {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();

    return (double) memoryUsage.getUsed();
}