Java Code Examples for java.lang.management.MemoryPoolMXBean#setUsageThreshold()

The following examples show how to use java.lang.management.MemoryPoolMXBean#setUsageThreshold() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UsageThresholdIncreasedTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
protected void runTest() {
    long headerSize = CodeCacheUtils.getHeaderSize(btype);
    long allocationUnit = Math.max(0, CodeCacheUtils.MIN_ALLOCATION - headerSize);
    MemoryPoolMXBean bean = btype.getMemoryPool();
    long initialCount = bean.getUsageThresholdCount();
    long initialSize = bean.getUsage().getUsed();
    bean.setUsageThreshold(initialSize + THRESHOLD_STEP);
    for (int i = 0; i < ALLOCATION_STEP - 1; i++) {
        CodeCacheUtils.WB.allocateCodeBlob(allocationUnit, btype.id);
    }
    // Usage threshold check is triggered by GC cycle, so, call it
    CodeCacheUtils.WB.fullGC();
    checkUsageThresholdCount(bean, initialCount);
    long filledSize = bean.getUsage().getUsed();
    bean.setUsageThreshold(filledSize + THRESHOLD_STEP);
    for (int i = 0; i < ALLOCATION_STEP - 1; i++) {
        CodeCacheUtils.WB.allocateCodeBlob(allocationUnit, btype.id);
    }
    CodeCacheUtils.WB.fullGC();
    checkUsageThresholdCount(bean, initialCount);
    System.out.println("INFO: Case finished successfully for " + bean.getName());
}
 
Example 2
Source File: UsageThresholdNotExceededTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
protected void runTest() {
    MemoryPoolMXBean bean = btype.getMemoryPool();
    long initialThresholdCount = bean.getUsageThresholdCount();
    long initialUsage = bean.getUsage().getUsed();

    bean.setUsageThreshold(initialUsage + 1 + CodeCacheUtils.MIN_ALLOCATION);
    long size = CodeCacheUtils.getHeaderSize(btype);

    CodeCacheUtils.WB.allocateCodeBlob(Math.max(0, CodeCacheUtils.MIN_ALLOCATION
            - size), btype.id);
    // a gc cycle triggers usage threshold recalculation
    CodeCacheUtils.WB.fullGC();
    CodeCacheUtils.assertEQorGTE(btype, bean.getUsageThresholdCount(), initialThresholdCount,
            String.format("Usage threshold was hit: %d times for %s. "
                    + "Threshold value: %d with current usage: %d",
                    bean.getUsageThresholdCount(), bean.getName(),
                    bean.getUsageThreshold(), bean.getUsage().getUsed()));
    System.out.println("INFO: Case finished successfully for " + bean.getName());
}
 
Example 3
Source File: MemoryWatchdog.java    From pitest with Apache License 2.0 6 votes vote down vote up
public static void addWatchDogToAllPools(final long threshold,
    final NotificationListener listener) {
  final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  final NotificationEmitter ne = (NotificationEmitter) memBean;

  ne.addNotificationListener(listener, null, null);

  final List<MemoryPoolMXBean> memPools = ManagementFactory
      .getMemoryPoolMXBeans();
  for (final MemoryPoolMXBean mp : memPools) {
    if (mp.isUsageThresholdSupported()) {
      final MemoryUsage mu = mp.getUsage();
      final long max = mu.getMax();
      final long alert = (max * threshold) / 100;
      // LOG.info("Setting a threshold shutdown on pool: " + mp.getName()
      // + " for: " + alert);
      mp.setUsageThreshold(alert);

    }
  }
}
 
Example 4
Source File: PerformanceWatcher.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void watchCodeCache(final MemoryPoolMXBean bean) {
  final long threshold = bean.getUsage().getMax() - 5 * 1024 * 1024;
  if (!bean.isUsageThresholdSupported() || threshold <= 0) return;

  bean.setUsageThreshold(threshold);
  final NotificationEmitter emitter = (NotificationEmitter)ManagementFactory.getMemoryMXBean();
  emitter.addNotificationListener(new NotificationListener() {
    @Override
    public void handleNotification(Notification n, Object hb) {
      if (bean.getUsage().getUsed() > threshold) {
        LOG.info("Code Cache is almost full");
        dumpThreads("codeCacheFull", true);
        try {
          emitter.removeNotificationListener(this);
        }
        catch (ListenerNotFoundException e) {
          LOG.error(e);
        }
      }
    }
  }, null, null);
}
 
Example 5
Source File: CodeCacheUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static final void hitUsageThreshold(MemoryPoolMXBean bean,
        BlobType btype) {
    long initialSize = bean.getUsage().getUsed();
    bean.setUsageThreshold(initialSize + 1);
    long usageThresholdCount = bean.getUsageThresholdCount();
    long addr = WB.allocateCodeBlob(1, btype.id);
    WB.fullGC();
    Utils.waitForCondition(()
            -> bean.getUsageThresholdCount() == usageThresholdCount + 1);
    WB.freeCodeBlob(addr);
}
 
Example 6
Source File: MemoryMonitor.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void setPercentageUsageThreshold(double percentage) {
    for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
        if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
            if (percentage <= 0.0 || percentage > 1.0) {
                throw new IllegalArgumentException("percentage not in range");
            }
            long warningThreshold = (long) (pool.getUsage().getMax() * percentage);
            pool.setUsageThreshold(warningThreshold);
        }
    }
}
 
Example 7
Source File: VMLogger.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void enableOptionalFunctionality()  {
    try {
        // ClassLoadingMXBean operations
        classBean.setVerbose(true);

        // MemoryMXBean operations
        memBean.setVerbose(true);

        // MemoryPoolMXBean operations
        for (MemoryPoolMXBean memPoolBean: memPoolBeans) {
            memPoolBean.resetPeakUsage();

            if (memPoolBean.isCollectionUsageThresholdSupported()) {
                memPoolBean.setCollectionUsageThreshold(10000);
            }

            if (memPoolBean.isUsageThresholdSupported()) {
                memPoolBean.setUsageThreshold(200000);
            }            
        }

        // ThreadMXBean operations
        threadBean.resetPeakThreadCount();

        if (threadBean.isThreadContentionMonitoringSupported()) {
            threadBean.setThreadContentionMonitoringEnabled(true);
        }

        if (threadBean.isThreadCpuTimeSupported()) {
            threadBean.setThreadCpuTimeEnabled(true);
        }
        
        // LoggingMXBean operations
        List<String> loggers = logBean.getLoggerNames();
        
        String[] levels = {"SEVERE", "WARNING", "INFO", "CONFIG", "FINE", "FINER", "FINEST"};
        int i = 0;
        
        for( String logger : loggers) {               	
            if (i > 6) {
            	i = i - 7;
            }
            
            // There's a chance the logger no longer exists
            String parent = logBean.getParentLoggerName(logger);
            if (parent != null) {
            	logBean.setLoggerLevel(logger, levels[i]);
            }
            
            i++;                
        }
        
    } catch (UnsupportedOperationException uoe) {
        Message.logOut("One of the operations you tried is not supported");
        uoe.printStackTrace();
    }
}
 
Example 8
Source File: PoolsIndependenceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
protected void runTest() {
    MemoryPoolMXBean bean = btype.getMemoryPool();
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
            addNotificationListener(this, null, null);
    bean.setUsageThreshold(bean.getUsage().getUsed() + 1);
    long beginTimestamp = System.currentTimeMillis();
    CodeCacheUtils.WB.allocateCodeBlob(
            CodeCacheUtils.ALLOCATION_SIZE, btype.id);
    CodeCacheUtils.WB.fullGC();
    /* waiting for expected event to be received plus double the time took
     to receive expected event(for possible unexpected) and
     plus 1 second in case expected event received (almost)immediately */
    Utils.waitForCondition(() -> {
        long currentTimestamp = System.currentTimeMillis();
        int eventsCount
                = counters.get(btype.getMemoryPool().getName()).get();
        if (eventsCount > 0) {
            if (eventsCount > 1) {
                return true;
            }
            long timeLastEventTook
                    = beginTimestamp - lastEventTimestamp;
            long timeoutValue
                    = 1000L + beginTimestamp + 3L * timeLastEventTook;
            return currentTimestamp > timeoutValue;
        }
        return false;
    });
    for (BlobType bt : BlobType.getAvailable()) {
        int expectedNotificationsAmount = bt.equals(btype) ? 1 : 0;
        CodeCacheUtils.assertEQorGTE(btype, counters.get(bt.getMemoryPool().getName()).get(),
                expectedNotificationsAmount, String.format("Unexpected "
                        + "amount of notifications for pool: %s",
                        bt.getMemoryPool().getName()));
    }
    try {
        ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
                removeNotificationListener(this);
    } catch (ListenerNotFoundException ex) {
        throw new AssertionError("Can't remove notification listener", ex);
    }
    System.out.printf("INFO: Scenario with %s finished%n", bean.getName());
}
 
Example 9
Source File: Fawe.java    From FastAsyncWorldedit with GNU General Public License v3.0 4 votes vote down vote up
private void setupMemoryListener() {
    if (Settings.IMP.MAX_MEMORY_PERCENT < 1 || Settings.IMP.MAX_MEMORY_PERCENT > 99) {
        return;
    }
    try {
        final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
        final NotificationEmitter ne = (NotificationEmitter) memBean;

        ne.addNotificationListener(new NotificationListener() {
            @Override
            public void handleNotification(final Notification notification, final Object handback) {
                final long heapSize = Runtime.getRuntime().totalMemory();
                final long heapMaxSize = Runtime.getRuntime().maxMemory();
                if (heapSize < heapMaxSize) {
                    return;
                }
                MemUtil.memoryLimitedTask();
            }
        }, null, null);

        final List<MemoryPoolMXBean> memPools = ManagementFactory.getMemoryPoolMXBeans();
        for (final MemoryPoolMXBean mp : memPools) {
            if (mp.isUsageThresholdSupported()) {
                final MemoryUsage mu = mp.getUsage();
                final long max = mu.getMax();
                if (max < 0) {
                    continue;
                }
                final long alert = (max * Settings.IMP.MAX_MEMORY_PERCENT) / 100;
                mp.setUsageThreshold(alert);
            }
        }
    } catch (Throwable e) {
        debug("====== MEMORY LISTENER ERROR ======");
        MainUtil.handleError(e, false);
        debug("===================================");
        debug("FAWE needs access to the JVM memory system:");
        debug(" - Change your Java security settings");
        debug(" - Disable this with `max-memory-percent: -1`");
        debug("===================================");
    }
}
 
Example 10
Source File: SpillableMemoryManager.java    From spork with Apache License 2.0 4 votes vote down vote up
private SpillableMemoryManager() {
    ((NotificationEmitter)ManagementFactory.getMemoryMXBean()).addNotificationListener(this, null, null);
    List<MemoryPoolMXBean> mpbeans = ManagementFactory.getMemoryPoolMXBeans();
    MemoryPoolMXBean tenuredHeap = null;
    long tenuredHeapSize = 0;
    long totalSize = 0;
    for (MemoryPoolMXBean pool : mpbeans) {
        log.debug("Found heap (" + pool.getName() + ") of type " + pool.getType());
        if (pool.getType() == MemoryType.HEAP) {
            long size = pool.getUsage().getMax();
            totalSize += size;
            // CMS Old Gen or "tenured" is the only heap that supports
            // setting usage threshold.
            if (pool.isUsageThresholdSupported()) {
                tenuredHeapSize = size;
                tenuredHeap = pool;
            }
        }
    }
    extraGCSpillSizeThreshold  = (long) (totalSize * extraGCThresholdFraction);
    if (tenuredHeap == null) {
        throw new RuntimeException("Couldn't find heap");
    }
    log.debug("Selected heap to monitor (" +
        tenuredHeap.getName() + ")");

    // we want to set both collection and usage threshold alerts to be
    // safe. In some local tests after a point only collection threshold
    // notifications were being sent though usage threshold notifications
    // were sent early on. So using both would ensure that
    // 1) we get notified early (though usage threshold exceeded notifications)
    // 2) we get notified always when threshold is exceeded (either usage or
    //    collection)

    /* We set the threshold to be 50% of tenured since that is where
     * the GC starts to dominate CPU time according to Sun doc */
    tenuredHeap.setCollectionUsageThreshold((long)(tenuredHeapSize * collectionMemoryThresholdFraction));
    // we set a higher threshold for usage threshold exceeded notification
    // since this is more likely to be effective sooner and we do not
    // want to be spilling too soon
    tenuredHeap.setUsageThreshold((long)(tenuredHeapSize * memoryThresholdFraction));
}