Java 类java.lang.management.MemoryUsage 实例源码

项目:openjdk-jdk10    文件:MemoryPoolStat.java   
MemoryPoolStat(String name,
               long usageThreshold,
               MemoryUsage usage,
               long lastGcId,
               long lastGcStartTime,
               long lastGcEndTime,
               long collectThreshold,
               MemoryUsage beforeGcUsage,
               MemoryUsage afterGcUsage) {
    this.poolName = name;
    this.usageThreshold = usageThreshold;
    this.usage = usage;
    this.lastGcId = lastGcId;
    this.lastGcStartTime = lastGcStartTime;
    this.lastGcEndTime = lastGcEndTime;
    this.collectThreshold = collectThreshold;
    this.beforeGcUsage = beforeGcUsage;
    this.afterGcUsage = afterGcUsage;
}
项目:openjdk-jdk10    文件:TestNewSizeFlags.java   
/**
 *  Get young gen memory usage.
 *
 *  For G1 it is EdenUsage + SurvivorUsage,
 *  for other GCs it is EdenUsage + 2 * SurvivorUsage.
 *  For G1 max value is just LONG_MAX.
 *  For all GCs used value is 0.
 */
private static MemoryUsage getYoungGenUsage() {
    MemoryUsage edenUsage = HeapRegionUsageTool.getEdenUsage();
    MemoryUsage survivorUsage = HeapRegionUsageTool.getSurvivorUsage();
    long edenUsageInit = edenUsage.getInit();
    long edenUsageCommited = edenUsage.getCommitted();
    long survivorUsageInit = survivorUsage.getInit();
    long survivorUsageCommited = survivorUsage.getCommitted();

    if (YOUNG_GC_TYPE == GCTypes.YoungGCType.G1) {
        return new MemoryUsage(edenUsageInit + survivorUsageInit, 0,
                edenUsageCommited + survivorUsageCommited, Long.MAX_VALUE);
    } else {
        return new MemoryUsage(edenUsageInit + survivorUsageInit * 2, 0,
                edenUsageCommited + survivorUsageCommited * 2,
                edenUsage.getMax() + survivorUsage.getMax() * 2);
    }
}
项目:openjdk-jdk10    文件:GarbageProducer.java   
private List<Object> eatMetaspace(float targetUsage) {
    List<Object> list = new ArrayList<>();
    MemoryPoolMXBean metaspacePool = getMatchedMemoryPool(".*Metaspace.*");
    float currentUsage;
    GeneratedClassProducer gp = new GeneratedClassProducer();
    do {
        try {
            list.add(gp.create(0));
        } catch (OutOfMemoryError oome) {
            list = null;
            throw new RuntimeException("Unexpected OOME '" + oome.getMessage() + "' while eating " + targetUsage + " of Metaspace.");
        }
        MemoryUsage memoryUsage = metaspacePool.getUsage();
        currentUsage = (((float) memoryUsage.getUsed()) / memoryUsage.getMax());
    } while (currentUsage < targetUsage);
    return list;
}
项目:GameResourceBot    文件:Commands.java   
public static void status(Scanner scanner, Message message) {
    StringBuffer buffer = new StringBuffer();
    buffer.append("My Memory:\n\n");
    buffer.append("\n\n");
    for (MemPool pool : getPools()) {
        MemoryUsage usage = pool.getUsage();
        buffer.append(pool.getName()).append("\n");
        buffer.append("\tINIT:     ").append(FileUtils.byteCountToDisplaySize(usage.getInit()))
                .append("\n");
        buffer.append("\tUSED:     ").append(FileUtils.byteCountToDisplaySize(usage.getUsed()))
                .append("\n");
        buffer.append("\tCOMMITED: ")
                .append(FileUtils.byteCountToDisplaySize(usage.getCommitted())).append("\n");
        buffer.append("\tMAX:      ").append(FileUtils.byteCountToDisplaySize(usage.getMax()))
                .append("\n");
    }
    Speaker.sayCode(message.getChannel(), buffer.toString());
}
项目:QDrill    文件:MemoryIterator.java   
@Override
public Object next() {
  if (!beforeFirst) {
    throw new IllegalStateException();
  }
  beforeFirst = false;
  final MemoryInfo memoryInfo = new MemoryInfo();

  final DrillbitEndpoint endpoint = context.getIdentity();
  memoryInfo.hostname = endpoint.getAddress();
  memoryInfo.user_port = endpoint.getUserPort();

  final MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  memoryInfo.heap_current = heapMemoryUsage.getUsed();
  memoryInfo.heap_max = heapMemoryUsage.getMax();

  BufferPoolMXBean directBean = getDirectBean();
  memoryInfo.jvm_direct_current = directBean.getMemoryUsed();


  memoryInfo.direct_current = context.getDrillbitContext().getAllocator().getAllocatedMemory();
  memoryInfo.direct_max = TopLevelAllocator.MAXIMUM_DIRECT_MEMORY;
  return memoryInfo;
}
项目:OpenJSharp    文件:MemoryPoolStat.java   
MemoryPoolStat(String name,
               long usageThreshold,
               MemoryUsage usage,
               long lastGcId,
               long lastGcStartTime,
               long lastGcEndTime,
               long collectThreshold,
               MemoryUsage beforeGcUsage,
               MemoryUsage afterGcUsage) {
    this.poolName = name;
    this.usageThreshold = usageThreshold;
    this.usage = usage;
    this.lastGcId = lastGcId;
    this.lastGcStartTime = lastGcStartTime;
    this.lastGcEndTime = lastGcEndTime;
    this.collectThreshold = collectThreshold;
    this.beforeGcUsage = beforeGcUsage;
    this.afterGcUsage = afterGcUsage;
}
项目:OpenJSharp    文件:GcInfo.java   
private GcInfo(GcInfoBuilder builder,
               long index, long startTime, long endTime,
               MemoryUsage[] muBeforeGc,
               MemoryUsage[] muAfterGc,
               Object[] extAttributes) {
    this.builder       = builder;
    this.index         = index;
    this.startTime     = startTime;
    this.endTime       = endTime;
    String[] poolNames = builder.getPoolNames();
    this.usageBeforeGc = new HashMap<String, MemoryUsage>(poolNames.length);
    this.usageAfterGc = new HashMap<String, MemoryUsage>(poolNames.length);
    for (int i = 0; i < poolNames.length; i++) {
        this.usageBeforeGc.put(poolNames[i],  muBeforeGc[i]);
        this.usageAfterGc.put(poolNames[i],  muAfterGc[i]);
    }
    this.extAttributes = extAttributes;
    this.cdata = new GcInfoCompositeData(this, builder, extAttributes);
}
项目:aws-sdk-java-v2    文件:Memory.java   
/**
 * Returns a summary information about the memory pools.
 */
public static String poolSummaries() {
    // Why ? list-archive?4273859
    // How ? http://stackoverflow.com/questions/697336/how-do-i-programmatically-find-out-my-permgen-space-usage
    //       http://stackoverflow.com/questions/8356416/xxmaxpermsize-with-or-without-xxpermsize
    StringBuilder sb = new StringBuilder();
    Iterator<MemoryPoolMXBean> iter =
            ManagementFactory.getMemoryPoolMXBeans().iterator();
    while (iter.hasNext()) {
        MemoryPoolMXBean item = iter.next();
        String name = item.getName();
        MemoryType type = item.getType();
        MemoryUsage usage = item.getUsage();
        MemoryUsage peak = item.getPeakUsage();
        MemoryUsage collections = item.getCollectionUsage();
        sb.append(String.format("Memory pool name: " + name
                                + ", type: " + type
                                + ", usage: " + usage
                                + ", peak: " + peak
                                + ", collections: " + collections
                                + "\n"));
    }
    return sb.toString();
}
项目:dremio-oss    文件:MemoryIterator.java   
@Override
public Object next() {
  if (!beforeFirst) {
    throw new IllegalStateException();
  }
  beforeFirst = false;
  final MemoryInfo memoryInfo = new MemoryInfo();

  final NodeEndpoint endpoint = dbContext.getEndpoint();
  memoryInfo.hostname = endpoint.getAddress();
  memoryInfo.fabric_port = endpoint.getFabricPort();

  final MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  memoryInfo.heap_current = heapMemoryUsage.getUsed();
  memoryInfo.heap_max = heapMemoryUsage.getMax();

  BufferPoolMXBean directBean = getDirectBean();
  memoryInfo.jvm_direct_current = directBean.getMemoryUsed();


  memoryInfo.direct_current = dbContext.getAllocator().getAllocatedMemory();
  memoryInfo.direct_max = SabotConfig.getMaxDirectMemory();
  return memoryInfo;
}
项目:openjdk-jdk10    文件:MemoryImpl.java   
static void createNotification(String notifType,
                               String poolName,
                               MemoryUsage usage,
                               long count) {
    MemoryImpl mbean = (MemoryImpl) ManagementFactory.getMemoryMXBean();
    if (!mbean.hasListeners()) {
        // if no listener is registered.
        return;
    }
    long timestamp = System.currentTimeMillis();
    String msg = getNotifMsg(notifType);
    Notification notif = new Notification(notifType,
                                          mbean.getObjectName(),
                                          getNextSeqNumber(),
                                          timestamp,
                                          msg);
    MemoryNotificationInfo info =
        new MemoryNotificationInfo(poolName,
                                   usage,
                                   count);
    CompositeData cd =
        MemoryNotifInfoCompositeData.toCompositeData(info);
    notif.setUserData(cd);
    mbean.sendNotification(notif);
}
项目:jdk8u-jdk    文件:MemoryImpl.java   
static void createNotification(String notifType,
                               String poolName,
                               MemoryUsage usage,
                               long count) {
    MemoryImpl mbean = (MemoryImpl) ManagementFactory.getMemoryMXBean();
    if (!mbean.hasListeners()) {
        // if no listener is registered.
        return;
    }
    long timestamp = System.currentTimeMillis();
    String msg = getNotifMsg(notifType);
    Notification notif = new Notification(notifType,
                                          mbean.getObjectName(),
                                          getNextSeqNumber(),
                                          timestamp,
                                          msg);
    MemoryNotificationInfo info =
        new MemoryNotificationInfo(poolName,
                                   usage,
                                   count);
    CompositeData cd =
        MemoryNotifInfoCompositeData.toCompositeData(info);
    notif.setUserData(cd);
    mbean.sendNotification(notif);
}
项目:openjdk-jdk10    文件:TestDynShrinkHeap.java   
private final void test() {
    System.gc();
    MemoryUsagePrinter.printMemoryUsage("init");

    eat();
    MemoryUsagePrinter.printMemoryUsage("eaten");
    MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

    free();
    MemoryUsagePrinter.printMemoryUsage("free");
    MemoryUsage muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

    assertLessThan(muFree.getCommitted(), muFull.getCommitted(), String.format(
            "committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
            + "%s = %s%n%s = %s",
            MIN_FREE_RATIO_FLAG_NAME,
            ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
                .getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
            MAX_FREE_RATIO_FLAG_NAME,
            ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
                .getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
    ));
}
项目:ditb    文件:CacheConfig.java   
/**
 * @param c Configuration to use.
 * @param mu JMX Memory Bean
 * @return Returns L2 block cache instance (for now it is BucketCache BlockCache all the time)
 * or null if not supposed to be a L2.
 */
private static BlockCache getL2(final Configuration c, final MemoryUsage mu) {
  final boolean useExternal = c.getBoolean(EXTERNAL_BLOCKCACHE_KEY, EXTERNAL_BLOCKCACHE_DEFAULT);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Trying to use " + (useExternal?" External":" Internal") + " l2 cache");
  }

  // If we want to use an external block cache then create that.
  if (useExternal) {
    return getExternalBlockcache(c);
  }

  // otherwise use the bucket cache.
  return getBucketCache(c, mu);

}
项目:jsf-core    文件:RegistryStatusServiceImpl.java   
@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);
}
项目:openjdk-jdk10    文件:TestHumongousShrinkHeap.java   
private final void test() {
    System.gc();
    MemoryUsagePrinter.printMemoryUsage("init");

    allocate();
    MemoryUsagePrinter.printMemoryUsage("allocated");
    MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

    free();
    MemoryUsagePrinter.printMemoryUsage("free");
    MemoryUsage muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

    assertLessThan(muFree.getCommitted(), muFull.getCommitted(), String.format(
            "committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
            + "%s = %s%n%s = %s",
            MIN_FREE_RATIO_FLAG_NAME,
            ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
                .getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
            MAX_FREE_RATIO_FLAG_NAME,
            ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class)
                .getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
    ));
}
项目:openjdk-jdk10    文件:GcInfoCompositeData.java   
public static Map<String, MemoryUsage>
        getMemoryUsageAfterGc(CompositeData cd) {
    try {
        TabularData td = (TabularData) cd.get(MEMORY_USAGE_AFTER_GC);
        //return (Map<String,MemoryUsage>)
        return cast(memoryUsageMapType.toJavaTypeData(td));
    } catch (InvalidObjectException | OpenDataException e) {
        // Should never reach here
        throw new AssertionError(e);
    }
}
项目:Reer    文件:GarbageCollectionStats.java   
static long calculateMaxSize(Set<GarbageCollectionEvent> events) {
    if (events.size() < 1) {
        return -1;
    }

    // Maximum pool size is fixed, so we should only need to get it from the first event
    MemoryUsage usage = events.iterator().next().getUsage();
    return usage.getMax();
}
项目:openjdk-jdk10    文件:GcInfoCompositeData.java   
public static Map<String, MemoryUsage>
        getMemoryUsageBeforeGc(CompositeData cd) {
    try {
        TabularData td = (TabularData) cd.get(MEMORY_USAGE_BEFORE_GC);
        return cast(memoryUsageMapType.toJavaTypeData(td));
    } catch (InvalidObjectException | OpenDataException e) {
        // Should never reach here
        throw new AssertionError(e);
    }
}
项目:openjdk-jdk10    文件:MemoryPoolImpl.java   
void triggerAction(MemoryUsage usage) {
    // create and send notification
    MemoryImpl.createNotification(MEMORY_THRESHOLD_EXCEEDED,
                                  pool.getName(),
                                  usage,
                                  getCount());
}
项目:ditb    文件:HeapMemoryManager.java   
@Override
protected void chore() {
  // Sample heap occupancy
  MemoryUsage memUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  heapOccupancyPercent = (float)memUsage.getUsed() / (float)memUsage.getCommitted();
  // If we are above the heap occupancy alarm low watermark, switch to short
  // sleeps for close monitoring. Stop autotuning, we are in a danger zone.
  if (heapOccupancyPercent >= heapOccupancyLowWatermark) {
    if (!alarming) {
      LOG.warn("heapOccupancyPercent " + heapOccupancyPercent +
        " is above heap occupancy alarm watermark (" + heapOccupancyLowWatermark + ")");
      alarming = true;
    }

    triggerNow();
    try {
      // Need to sleep ourselves since we've told the chore's sleeper
      // to skip the next sleep cycle.
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      // Interrupted, propagate
      Thread.currentThread().interrupt();
    }
  } else {
    if (alarming) {
      LOG.info("heapOccupancyPercent " + heapOccupancyPercent +
        " is now below the heap occupancy alarm watermark (" +
        heapOccupancyLowWatermark + ")");
      alarming = false;
    }
  }
  // Autotune if tuning is enabled and allowed
  if (tunerOn && !alarming) {
    tune();
  }
}
项目:ditb    文件:CacheConfig.java   
/**
 * Returns the block cache or <code>null</code> in case none should be used.
 * Sets GLOBAL_BLOCK_CACHE_INSTANCE
 *
 * @param conf  The current configuration.
 * @return The block cache or <code>null</code>.
 */
public static synchronized BlockCache instantiateBlockCache(Configuration conf) {
  if (GLOBAL_BLOCK_CACHE_INSTANCE != null) return GLOBAL_BLOCK_CACHE_INSTANCE;
  if (blockCacheDisabled) return null;
  MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  LruBlockCache l1 = getL1(conf, mu);
  // blockCacheDisabled is set as a side-effect of getL1(), so check it again after the call.
  if (blockCacheDisabled) return null;
  BlockCache l2 = getL2(conf, mu);
  if (l2 == null) {
    GLOBAL_BLOCK_CACHE_INSTANCE = l1;
  } else {
    boolean useExternal = conf.getBoolean(EXTERNAL_BLOCKCACHE_KEY, EXTERNAL_BLOCKCACHE_DEFAULT);
    boolean combinedWithLru = conf.getBoolean(BUCKET_CACHE_COMBINED_KEY,
      DEFAULT_BUCKET_CACHE_COMBINED);
    if (useExternal) {
      GLOBAL_BLOCK_CACHE_INSTANCE = new InclusiveCombinedBlockCache(l1, l2);
    } else {
      if (combinedWithLru) {
        GLOBAL_BLOCK_CACHE_INSTANCE = new CombinedBlockCache(l1, l2);
      } else {
        // L1 and L2 are not 'combined'.  They are connected via the LruBlockCache victimhandler
        // mechanism.  It is a little ugly but works according to the following: when the
        // background eviction thread runs, blocks evicted from L1 will go to L2 AND when we get
        // a block from the L1 cache, if not in L1, we will search L2.
        GLOBAL_BLOCK_CACHE_INSTANCE = l1;
      }
    }
    l1.setVictimCache(l2);
  }
  return GLOBAL_BLOCK_CACHE_INSTANCE;
}
项目:sstore-soft    文件:SystemStatsCollector.java   
/**
 * 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();
}
项目:otus_java_2017_10    文件:MemoryUtil.java   
private static void appendMemUsage(StringBuilder sb, Map<String, MemoryUsage> memUsage) {
    for(Map.Entry<String, MemoryUsage> entry: memUsage.entrySet()) {
        if (memRegions.get(entry.getKey()).isHeap()) {
            sb.append(entry.getKey()).append(" used=")
                    .append(entry.getValue().getUsed() >> 10)
                    .append("K; ");
        }
    }
}
项目:hadoop-oss    文件:JvmMetrics.java   
private void getMemoryUsage(MetricsRecordBuilder rb) {
  MemoryUsage memNonHeap = memoryMXBean.getNonHeapMemoryUsage();
  MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage();
  Runtime runtime = Runtime.getRuntime();
  rb.addGauge(MemNonHeapUsedM, memNonHeap.getUsed() / M)
    .addGauge(MemNonHeapCommittedM, memNonHeap.getCommitted() / M)
    .addGauge(MemNonHeapMaxM, calculateMaxMemoryUsage(memNonHeap))
    .addGauge(MemHeapUsedM, memHeap.getUsed() / M)
    .addGauge(MemHeapCommittedM, memHeap.getCommitted() / M)
    .addGauge(MemHeapMaxM, calculateMaxMemoryUsage(memHeap))
    .addGauge(MemMaxM, runtime.maxMemory() / M);
}
项目:openjdk-jdk10    文件:TestDynShrinkHeap.java   
public static void printMemoryUsage(String label) {
    MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
    System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
            label,
            NF.format(memusage.getInit()),
            NF.format(memusage.getUsed()),
            NF.format(memusage.getCommitted()),
            freeratio * 100
    );
}
项目:tomcat7    文件:Diagnostics.java   
/**
 * Format contents of a MemoryUsage object.
 * @param name a text prefix used in formatting
 * @param usage the MemoryUsage object to format
 * @return the formatted contents
 */
private static String formatMemoryUsage(String name, MemoryUsage usage) {
    if (usage != null) {
        StringBuilder sb = new StringBuilder();
        sb.append(INDENT1 + name + " init: " + usage.getInit() + CRLF);
        sb.append(INDENT1 + name + " used: " + usage.getUsed() + CRLF);
        sb.append(INDENT1 + name + " committed: " + usage.getCommitted() + CRLF);
        sb.append(INDENT1 + name + " max: " + usage.getMax() + CRLF);
        return sb.toString();
    }
    return "";
}
项目:convertigo-engine    文件:UsageMonitor.java   
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;
}
项目:s-store    文件:SystemStatsCollector.java   
/**
 * 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();
}
项目:openjdk-jdk10    文件:TestSurvivorRatioFlag.java   
private static void verifyPSSurvivorRatio(int expectedRatio) {
    MemoryUsage edenUsage = HeapRegionUsageTool.getEdenUsage();
    MemoryUsage survivorUsage = HeapRegionUsageTool.getSurvivorUsage();

    long youngGenSize = edenUsage.getMax() + 2 * survivorUsage.getMax();
    // for Paralle GC Min/InitialSurvivorRatio = SurvivorRatio + 2
    long expectedSize = HeapRegionUsageTool.alignDown(youngGenSize / (expectedRatio + 2),
            wb.psHeapGenerationAlignment());

    if (expectedSize != survivorUsage.getCommitted()) {
        throw new RuntimeException("Expected survivor size is: " + expectedSize
                + ", but observed size is: " + survivorUsage.getCommitted());
    }
}
项目:OpenJSharp    文件:GcInfoBuilder.java   
GcInfo getLastGcInfo() {
    MemoryUsage[] usageBeforeGC = new MemoryUsage[poolNames.length];
    MemoryUsage[] usageAfterGC = new MemoryUsage[poolNames.length];
    Object[] values = new Object[gcExtItemCount];

    return getLastGcInfo0(gc, gcExtItemCount, values, gcExtItemTypes,
                          usageBeforeGC, usageAfterGC);
}
项目:openjdk-jdk10    文件:MemoryUsageCompositeData.java   
public static void badTypeCompositeData() throws Exception {
    final int K = 1024;
    final Object[] values = {
        new Integer(5 * K),
        new Long(1 * K),
        new Long(10 * K),
        new Long(2 * K),
        "Dummy",
        "Dummy",
    };

    CompositeType muct =
        new CompositeType("MyMemoryUsageCompositeType",
                          "CompositeType for MemoryUsage",
                          memoryUsageItemNames,
                          memoryUsageItemNames,
                          badMUItemTypes);
    CompositeData cd =
       new CompositeDataSupport(muct,
                                memoryUsageItemNames,
                                values);
    try {
        MemoryUsage u = MemoryUsage.from(cd);
    } catch (IllegalArgumentException e) {
        System.out.println("Expected exception: " +
            e.getMessage());
        return;
    }
    throw new RuntimeException(
        "IllegalArgumentException not thrown");
}
项目:java-memory-assistant    文件:JavaVirtualMachine.java   
@Override
public MemoryPool getHeapMemoryPool(final MemoryMXBean memoryBean) {
  return new MemoryPoolImpl(MemoryPool.Type.HEAP, new Supplier<MemoryUsage>() {
    @Override
    public MemoryUsage get() {
      return memoryBean.getHeapMemoryUsage();
    }
  });
}
项目:uavstack    文件:JVMToolHelper.java   
public static Map<String, Long> readHeapUsage(MemoryUsage mu) {

        Map<String, Long> m = new LinkedHashMap<String, Long>();

        m.put("heap_use", mu.getUsed());
        m.put("heap_commit", mu.getCommitted());
        m.put("heap_max", mu.getMax());
        m.put("heap_init", mu.getInit());

        return m;
    }
项目:OpenJSharp    文件:Sensor.java   
/**
 * Triggers this sensor piggybacking a memory usage object.
 * This method sets this sensor on
 * and increments the count with the input <tt>increment</tt>.
 */
public void trigger(int increment, MemoryUsage usage) {
    synchronized (lock) {
        on = true;
        count += increment;
        // Do something here...
    }
    triggerAction(usage);
}
项目:OpenJSharp    文件:JvmMemoryImpl.java   
private MemoryUsage getMemoryUsage(MemoryType type) {
    if (type == MemoryType.HEAP) {
        return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    } else {
        return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
    }
}
项目:OpenJSharp    文件:JvmMemoryImpl.java   
MemoryUsage getNonHeapMemoryUsage() {
    try {
        final Map<Object, Object> m = JvmContextFactory.getUserData();

        if (m != null) {
            final MemoryUsage cached = (MemoryUsage)
                m.get(nonHeapMemoryTag);
            if (cached != null) {
                log.debug("getNonHeapMemoryUsage",
                      "jvmMemory.getNonHeapMemoryUsage found in cache.");
                return cached;
            }

            final MemoryUsage u = getMemoryUsage(MemoryType.NON_HEAP);

            //  getNonHeapMemoryUsage() never returns null.
            //
            // if (u == null) u=MemoryUsage.INVALID;

            m.put(nonHeapMemoryTag,u);
            return u;
        }
        // Should never come here.
        // Log error!
        log.trace("getNonHeapMemoryUsage",
                  "ERROR: should never come here!");
        return getMemoryUsage(MemoryType.NON_HEAP);
    } catch (RuntimeException x) {
        log.trace("getNonHeapMemoryUsage",
              "Failed to get NonHeapMemoryUsage: " + x);
        log.debug("getNonHeapMemoryUsage",x);
        throw x;
    }

}
项目:openjdk-jdk10    文件:LogPrinter.java   
void printMemoryUsage() {
    if (options.verbose) {
        MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
        float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
        log.format(" [used: %-7s, comm: %-7s, freeRatio ~= %.1f%%]",
                        humanReadableByteCount(memusage.getUsed()),
                        humanReadableByteCount(memusage.getCommitted()),
                        freeratio * 100);
    }
}
项目:openjdk-jdk10    文件:TestSurvivorRatioFlag.java   
private static void verifyG1SurvivorRatio(int expectedRatio) {
    MemoryUsage survivorUsage = HeapRegionUsageTool.getSurvivorUsage();

    int regionSize = wb.g1RegionSize();
    int youngListLength = (int) Math.max(NEW_SIZE / regionSize, 1);
    int expectedSurvivorRegions = (int) Math.ceil(youngListLength / (double) expectedRatio);
    int observedSurvivorRegions = (int) (survivorUsage.getCommitted() / regionSize);

    if (expectedSurvivorRegions < observedSurvivorRegions) {
        throw new RuntimeException("Expected amount of G1 survivor regions is "
                + expectedSurvivorRegions + ", but observed "
                + observedSurvivorRegions);
    }
}
项目:OpenJSharp    文件:MemoryPoolImpl.java   
public boolean isCollectionUsageThresholdExceeded() {
    if (!isCollectionUsageThresholdSupported()) {
        throw new UnsupportedOperationException(
            "CollectionUsage threshold is not supported");
    }

    // return false if usage threshold crossing checking is disabled
    if (collectionThreshold == 0) {
        return false;
    }

    MemoryUsage u = getCollectionUsage0();
    return (gcSensor.isOn() ||
            (u != null && u.getUsed() >= collectionThreshold));
}
项目:OpenJSharp    文件:GcInfoCompositeData.java   
public static Map<String, MemoryUsage>
        getMemoryUsageBeforeGc(CompositeData cd) {
    try {
        TabularData td = (TabularData) cd.get(MEMORY_USAGE_BEFORE_GC);
        return cast(memoryUsageMapType.toJavaTypeData(td));
    } catch (InvalidObjectException | OpenDataException e) {
        // Should never reach here
        throw new AssertionError(e);
    }
}