public static void main(String[] args) {
    // We create an instance of a File to represent a partition
    // of our file system. For instance here we used a drive D:
    // as in Windows operating system.
    File file = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro/state/traps");
    File file2 = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro/state/");
    File file3 = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro");

    // Using the getTotalSpace() we can get an information of
    // the actual size of the partition, and we convert it to
    // mega bytes.
    long totalSpace = file.getTotalSpace() / (1024 * 1024);
    /*System.err.println("file.length :: "+getFolderSize(file));
    System.err.println("file2.length :: "+getFolderSize(file2));
    System.err.println("file3.length :: "+getFolderSize(file3));*/
    System.err.println(
        "file.sizeOfDirectory :: " + org.apache.commons.io.FileUtils.sizeOfDirectory(file3));

    // Next we get the free disk space as the name of the
    // method shown us, and also get the size in mega bytes.
    long freeSpace = file.getFreeSpace() / (1024 * 1024);

    // Just print out the values.
    System.out.println("Total Space1 = " + totalSpace + " Mega Bytes");
    System.out.println("Free Space1 = " + freeSpace + " Mega Bytes");

    System.out.println("Free Space3 = " + Runtime.getRuntime().totalMemory() + " Mega Bytes");
    System.out.println("Free Space4 = " + Runtime.getRuntime().freeMemory() + " Mega Bytes");
    System.out.println("Free Space5 = " + Runtime.getRuntime().maxMemory() + "Bytes");
    System.out.println(
        "Free Space6 = " + ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage() + "Bytes");
    System.out.println(
        "Free Space7 = " + ManagementFactory.getMemoryMXBean().getHeapMemoryUsage() + "Bytes");
    System.out.println("Free Space8 = " + file.getUsableSpace() / 1024 / 1024 + " Mega Bytes");
  }
 /** Add JVM heap metrics. */
 protected void addHeapMetrics(Collection<Metric<?>> result) {
   MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
   result.add(new Metric<Long>("heap.committed", memoryUsage.getCommitted() / 1024));
   result.add(new Metric<Long>("heap.init", memoryUsage.getInit() / 1024));
   result.add(new Metric<Long>("heap.used", memoryUsage.getUsed() / 1024));
   result.add(new Metric<Long>("heap", memoryUsage.getMax() / 1024));
 }
Example #3
0
  public void log() {
    new Thread(new LogRunnable()).start();

    List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans();
    MemoryPoolMXBean pool = null;
    for (MemoryPoolMXBean bean : beans) {
      if ("Tenured Gen".equals(bean.getName())) {
        pool = bean;
        break;
      }
    }

    MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    NotificationEmitter emitter = (NotificationEmitter) mbean;
    MemoryListener listener = new MemoryListener();
    emitter.addNotificationListener(listener, null, null);
    pool.setUsageThreshold(8 * 1024 * 1024);

    consumeMemory();
    System.gc();
    checkMemory(pool);
    consumeMemory();
    checkMemory(pool);
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Example #4
0
  public String getInodeLimitText() {
    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 used = (totalMemory * 100) / maxMemory;

    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(totalMemory)
            + " / "
            + StringUtils.byteDesc(maxMemory)
            + " ("
            + used
            + "%) <br>";
    return str;
  }
Example #5
0
  public static void main(String args[]) {

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

    long init = heapMemoryUsage.getInit();
    long used = heapMemoryUsage.getUsed();
    long max = heapMemoryUsage.getMax();
    long committed = heapMemoryUsage.getCommitted();
    long free = max - used;
    int usedPercent = (int) (used / max);
    int freePercent = (int) (usedPercent / max);

    MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

    List<GarbageCollectorMXBean> garbageCollectorMXBeans =
        ManagementFactory.getGarbageCollectorMXBeans();

    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();

    com.sun.management.OperatingSystemMXBean operatingSystemMXBean =
        (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    long commitVirtual = operatingSystemMXBean.getCommittedVirtualMemorySize();

    println(init, used, max, committed);
    println(commitVirtual);
  }
Example #6
0
  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.common.test.SpeedTest#startTimer(java.lang.String)
   */
  public void startTimer(final String iName) {
    Runtime.getRuntime().runFinalization();
    Runtime.getRuntime().gc();

    try {
      Thread.sleep(TIME_WAIT);
    } catch (InterruptedException e) {
    }

    final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
    final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

    currentTestName = iName;

    currentTestHeapCommittedMemory = heapMemoryUsage.getCommitted();
    currentTestHeapUsedMemory = heapMemoryUsage.getUsed();
    currentTestHeapMaxMemory = heapMemoryUsage.getMax();

    currentTestNonHeapCommittedMemory = nonHeapMemoryUsage.getCommitted();
    currentTestNonHeapUsedMemory = nonHeapMemoryUsage.getUsed();
    currentTestNonHeapMaxMemory = nonHeapMemoryUsage.getMax();

    System.out.println("-> Started the test of '" + currentTestName + "' (" + cycles + " cycles)");

    currentTestTimer = System.currentTimeMillis();
  }
  private void createRuntimeProps(MemberStateImpl memberState) {
    Runtime runtime = Runtime.getRuntime();
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    ClassLoadingMXBean clMxBean = ManagementFactory.getClassLoadingMXBean();
    MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemory = memoryMxBean.getHeapMemoryUsage();
    MemoryUsage nonHeapMemory = memoryMxBean.getNonHeapMemoryUsage();

    Map<String, Long> map = new HashMap<String, Long>();
    map.put(
        "runtime.availableProcessors", Integer.valueOf(runtime.availableProcessors()).longValue());
    map.put("date.startTime", runtimeMxBean.getStartTime());
    map.put("seconds.upTime", runtimeMxBean.getUptime());

    map.put("memory.maxMemory", runtime.maxMemory());
    map.put("memory.freeMemory", runtime.freeMemory());
    map.put("memory.totalMemory", runtime.totalMemory());
    map.put("memory.heapMemoryMax", heapMemory.getMax());
    map.put("memory.heapMemoryUsed", heapMemory.getUsed());
    map.put("memory.nonHeapMemoryMax", nonHeapMemory.getMax());
    map.put("memory.nonHeapMemoryUsed", nonHeapMemory.getUsed());
    map.put("runtime.totalLoadedClassCount", clMxBean.getTotalLoadedClassCount());
    map.put(
        "runtime.loadedClassCount", Integer.valueOf(clMxBean.getLoadedClassCount()).longValue());
    map.put("runtime.unloadedClassCount", clMxBean.getUnloadedClassCount());
    map.put("runtime.totalStartedThreadCount", threadMxBean.getTotalStartedThreadCount());
    map.put("runtime.threadCount", Integer.valueOf(threadMxBean.getThreadCount()).longValue());
    map.put(
        "runtime.peakThreadCount", Integer.valueOf(threadMxBean.getPeakThreadCount()).longValue());
    map.put(
        "runtime.daemonThreadCount",
        Integer.valueOf(threadMxBean.getDaemonThreadCount()).longValue());
    memberState.setRuntimeProps(map);
  }
  @Override
  public void closeOp(boolean abort) throws HiveException {

    // ricardoj checking mapper hashmap usage
    memoryMXBean = ManagementFactory.getMemoryMXBean();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    long usedMemory = memoryMXBean.getHeapMemoryUsage().getUsed();
    LOG.info("ricardoj memory usage after deleting tables: " + usedMemory / (1024 * 1024) + "MB");

    if (mapJoinTables != null) {
      for (HashMapWrapper<?, ?> hashTable : mapJoinTables.values()) {
        hashTable.close();
      }
    }

    mapJoinTables = null;
    // ricardoj
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    usedMemory = memoryMXBean.getHeapMemoryUsage().getUsed();
    LOG.info("ricardoj memory usage after deleting tables: " + usedMemory / (1024 * 1024) + "MB");

    super.closeOp(abort);
  }
 public void init(final ServletContext context, final Map<String, String> paras) {
   _startTime = new Date();
   _context = context;
   _sipFactory = (SipFactory) context.getAttribute(ServletContextConstants.SIP_FACTORY);
   _mrcpFactory = (MrcpFactory) context.getAttribute(ServletContextConstants.MRCP_FACTORY);
   _appJarUrl =
       _context.getRealPath("/")
           + "WEB-INF"
           + File.separator
           + "lib"
           + File.separator
           + "tropo.jar";
   _cache = Collections.synchronizedMap(new WeakHashMap<Object, Application>());
   _tmx = ManagementFactory.getThreadMXBean();
   _mmx = ManagementFactory.getMemoryMXBean();
   try {
     _tropoBuildDate = Utils.getManifestAttribute(_appJarUrl, "Build-Date");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildDate = "Unknown";
   }
   try {
     _tropoVersionNo = Utils.getManifestAttribute(_appJarUrl, "Version-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoVersionNo = "Unknown";
   }
   try {
     _tropoBuildNo = Utils.getManifestAttribute(_appJarUrl, "Build-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildNo = "Unknown";
   }
   LOG.info(toString() + " / " + getVersionNo() + " / " + getBuildNo());
 }
 public MemoryMonitor() {
   LOG.info("initializing");
   this.springContextId = "Unknown";
   ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);
   ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true);
   lowMemoryListener =
       new NotificationListener() {
         public void handleNotification(Notification n, Object hb) {
           if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
             Map<String, String> memoryUsageStatistics = new HashMap<String, String>();
             memoryUsageStatistics.put(
                 "MemoryMXBean: " + MemoryType.HEAP,
                 ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().toString());
             memoryUsageStatistics.put(
                 "MemoryMXBean:" + MemoryType.NON_HEAP,
                 ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().toString());
             for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
               memoryUsageStatistics.put(
                   "MemoryPoolMXBean: " + pool.getType(), pool.getUsage().toString());
             }
             for (Listener listener : listeners) {
               listener.memoryUsageLow(
                   springContextId,
                   memoryUsageStatistics,
                   Arrays.toString(
                       ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads()));
             }
           }
         }
       };
   ((NotificationEmitter) ManagementFactory.getMemoryMXBean())
       .addNotificationListener(lowMemoryListener, null, null);
 }
 // 90, 1
 private void __jamon_innerUnit__memoryStats(
     @SuppressWarnings({"unused", "hiding"}) final java.io.Writer jamonWriter,
     final MetricsRegionServerWrapper mWrap)
     throws java.io.IOException {
   // 94, 1
   jamonWriter.write(
       "<table class=\"table table-striped\">\n<tr>\n    <tr>\n        <th>Used Heap</th>\n        <th>Max Heap</th>\n        <th>Direct Memory Used</th>\n        <th>Direct Memory Configured</th>\n        <th>Memstore Size</th>\n    </tr>\n</tr>\n<tr>\n    <td>\n        ");
   // 106, 9
   org.jamon.escaping.Escaping.HTML.write(
       org.jamon.emit.StandardEmitter.valueOf(
           StringUtils.humanReadableInt(
               ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed())),
       jamonWriter);
   // 106, 111
   jamonWriter.write("\n    </td>\n    <td>\n        ");
   // 109, 9
   org.jamon.escaping.Escaping.HTML.write(
       org.jamon.emit.StandardEmitter.valueOf(
           StringUtils.humanReadableInt(
               ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax())),
       jamonWriter);
   // 109, 110
   jamonWriter.write("\n    </td>\n    <td>\n        ");
   // 112, 9
   org.jamon.escaping.Escaping.HTML.write(
       org.jamon.emit.StandardEmitter.valueOf(
           StringUtils.humanReadableInt(DirectMemoryUtils.getDirectMemoryUsage())),
       jamonWriter);
   // 112, 85
   jamonWriter.write("\n    </td>\n    <td>\n        ");
   // 115, 9
   org.jamon.escaping.Escaping.HTML.write(
       org.jamon.emit.StandardEmitter.valueOf(
           StringUtils.humanReadableInt(DirectMemoryUtils.getDirectMemorySize())),
       jamonWriter);
   // 115, 84
   jamonWriter.write("\n    </td>\n    <td>");
   // 117, 9
   org.jamon.escaping.Escaping.HTML.write(
       org.jamon.emit.StandardEmitter.valueOf(
           StringUtils.humanReadableInt(mWrap.getMemstoreSize())),
       jamonWriter);
   // 117, 68
   jamonWriter.write("</td>\n</tr>\n</table>\n");
 }
Example #12
0
 private void removeNotificationListener(NotificationListener notificationListener) {
   MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
   try {
     ((NotificationBroadcaster) mem).removeNotificationListener(notificationListener);
   } catch (ListenerNotFoundException lnfe) {
     log.error("error in removeNotificationListener");
     log.error(lnfe);
   }
 }
Example #13
0
 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);
 }
 public void stop() {
   try {
     removeAllListeners();
     ((NotificationEmitter) ManagementFactory.getMemoryMXBean())
         .removeNotificationListener(lowMemoryListener);
   } catch (ListenerNotFoundException ex) {
     LOG.error("Unable to unregister mbean listener", ex);
   }
 }
Example #15
0
  public void validateMemory(int mem) throws LicenseException {
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    long max = memoryBean.getHeapMemoryUsage().getMax();

    long conv = max / 1073741824;

    if (conv > mem) {
      throw new LicenseException("Too much memory allocated, decrease your XMX Limit");
    }
  }
  /**
   * Grid-enables method only if heap utilized over 80%. Otherwise, method method will proceed with
   * local execution without calling grid at all.
   *
   * @param gridify {@inheritDoc}
   * @param arg {@inheritDoc}
   * @return {@inheritDoc}
   * @throws GridException {@inheritDoc}
   */
  @Override
  public boolean isGridify(Annotation gridify, GridifyArgument arg) throws GridException {
    MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

    // If heap memory for the local node is above 80% of maximum heap
    // memory available, return true which means that method will
    // be grid-enabled. Otherwise, return false, which means that
    // method will execute locally without grid.
    return heap.getUsed() > 0.8 * heap.getMax();
  }
Example #17
0
 public SystemManager() {
   memoryBean = ManagementFactory.getMemoryMXBean();
   BufferPoolMXBean localBean = null;
   List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
   for (BufferPoolMXBean b : pools) {
     if (b.getName().equals("direct")) {
       localBean = b;
     }
   }
   directBean = localBean;
 }
Example #18
0
  /**
   * Monitors the heap usage after full gc run and tells Cleaner to free memory if mem usage is too
   * high. Stops new allocation if mem usage is critical.
   *
   * @author tomas
   */
  private static class HeapUsageMonitor implements javax.management.NotificationListener {
    MemoryMXBean _allMemBean = ManagementFactory.getMemoryMXBean(); // general
    MemoryPoolMXBean _oldGenBean;
    public long _gc_callback;

    HeapUsageMonitor() {
      int c = 0;
      for (MemoryPoolMXBean m : ManagementFactory.getMemoryPoolMXBeans()) {
        if (m.getType() != MemoryType.HEAP) // only interested in HEAP
        continue;
        if (m.isCollectionUsageThresholdSupported() && m.isUsageThresholdSupported()) {
          // should be Old pool, get called when memory is critical
          _oldGenBean = m;
          _gc_callback = MEM_MAX;
          // Really idiotic API: no idea what the usageThreshold is, so I have
          // to guess. Start high, catch IAE & lower by 1/8th and try again.
          while (true) {
            try {
              m.setCollectionUsageThreshold(_gc_callback);
              break;
            } catch (IllegalArgumentException iae) {
              // Do NOT log this exception, it is expected and unavoidable and
              // entirely handled.

              _gc_callback -= (_gc_callback >> 3);
            }
          }
          NotificationEmitter emitter = (NotificationEmitter) _allMemBean;
          emitter.addNotificationListener(this, null, m);
          ++c;
        }
      }
      assert c == 1;
    }

    /**
     * Callback routine called by JVM after full gc run. Has two functions: 1) sets the amount of
     * memory to be cleaned from the cache by the Cleaner 2) sets the CAN_ALLOC flag to false if
     * memory level is critical
     *
     * <p>The callback happens in a system thread, and hence not through the usual water.Boot loader
     * - and so any touched classes are in the wrong class loader and you end up with new classes
     * with uninitialized global vars. Limit to touching global vars in the Boot class.
     */
    public void handleNotification(Notification notification, Object handback) {
      String notifType = notification.getType();
      if (notifType.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
        // Memory used after this FullGC
        Boot.TIME_AT_LAST_GC = System.currentTimeMillis();
        Boot.HEAP_USED_AT_LAST_GC = _allMemBean.getHeapMemoryUsage().getUsed();
        Boot.kick_store_cleaner();
      }
    }
  }
  public static final void createDefaultCache() {

    long availableMemory =
        (long)
            (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax()
                * DEFAULT_HEAP_MEMORY_PERCENTAGE);
    CacheBuilder<String, BlockReader> builder =
        CacheBuilder.newBuilder().maximumWeight(availableMemory).weigher(new KVWeigher());

    singleCache = buildCache(builder);
  }
Example #20
0
  protected void updateMemory() {
    // Determining current memory usage state
    MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    usedMemory = mu.getUsed();
    allocatedMemory = mu.getCommitted();

    // Updating bar text
    setText(getMemoryBarText());

    // Updating view
    repaint();
  }
 @Before
 public void openFileSystem() throws Exception {
   conf = new Configuration();
   fs = FileSystem.getLocal(conf);
   testFilePath = new Path(workDir, "TestOrcFile." + testCaseName.getMethodName() + ".orc");
   fs.delete(testFilePath, false);
   // make sure constant memory is available for ORC always
   memoryPercent =
       (float) MEMORY_FOR_ORC
           / (float) ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax();
   conf.setFloat(HiveConf.ConfVars.HIVE_ORC_FILE_MEMORY_POOL.varname, memoryPercent);
 }
  private void footerJvmAction() {
    long jvmUsed = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
    long jvmMax = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax();

    double jvmFrac = ((double) jvmUsed) / ((double) jvmMax);
    display.jvmAvailLabel.setText(Utility.progressString(progressSize, jvmFrac));
    //
    display.footerExtraLabel.setText(
        String.format(
            "   %d logs, %sused, %smax",
            AllGroups.getLogCount(),
            Utility.byteString(jvmUsed, true, true, false, false),
            Utility.byteString(jvmMax, true, true, false, false)));

    // Debug.print("jvm %d %s", jvmFrac,
    // String.format("%d logs, %s used memory, %s max",
    // AllGroups.getLogCount(), Utility.byteString(jvmUsed, true, true,
    // false, false),
    // Utility.byteString(jvmMax, true, true, false, false))
    // );
  }
 /**
  * (Re)Create the cache by limiting percentage of the total heap memory
  *
  * @param concurrencyLevel
  * @param initialCapacity
  * @param heapMemPercentage
  * @return The cache.
  */
 public static final Cache<String, BlockReader> createCache(
     int concurrencyLevel, int initialCapacity, float heapMemPercentage) {
   CacheBuilder builder =
       CacheBuilder.newBuilder()
           .concurrencyLevel(concurrencyLevel)
           .initialCapacity(initialCapacity)
           .maximumWeight(
               (long)
                   (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax()
                       * heapMemPercentage))
           .weigher(new KVWeigher());
   return buildCache(builder);
 }
Example #24
0
 public static synchronized State release() {
   long now = System.currentTimeMillis();
   if (marks.empty())
     throw new RuntimeException(
         "TimeStiatistics: Called release() without a matching call to mark()");
   State m = marks.pop();
   m.garbageCounterDelta = garbageCounter.get() - m.garbageCounterMark;
   m.end = now;
   MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
   m.memoryUsedEnd = memoryUsage.getUsed();
   System.out.println(m.toString());
   return m;
 }
 /**
  * Creates a new instance. This can't be called outside of container b/c agents have no refs to
  * the singleton container. So we can be sure this method is going to create services just once.
  *
  * @param c Reference to the container.
  * @return The sole instance.
  * @throws NullPointerException If the reference to the {@link Container} is <code>null</code>.
  */
 public static PixelsServicesFactory getInstance(Container c) {
   if (c == null) throw new NullPointerException(); // An agent called this method?
   if (singleton == null) {
     registry = c.getRegistry();
     singleton = new PixelsServicesFactory();
     // Retrieve the maximum heap size.
     MemoryUsage usage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
     String message = "Heap memory usage: max " + usage.getMax();
     registry.getLogger().info(singleton, message);
     // percentage of memory used for caching.
     maxSize = (int) (RATIO * usage.getMax()) / FACTOR;
   }
   return singleton;
 }
Example #26
0
  /**
   * Puts a marker in the marker stack. Every call to this method should have a corresponding call
   * to {@link #release()}. Calls to this method may be nested.
   *
   * @param markName the name of the marker
   */
  public static synchronized void mark(String markName) {
    State marker = new State();
    marker.id = markName;
    marker.start = System.currentTimeMillis();
    MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    marker.memoryUsedStart = memoryUsage.getUsed();
    marker.garbageCounterMark = garbageCounter.get();

    marks.push(marker);
    System.out.println(
        "Set block marker \""
            + markName
            + "\", memory used "
            + Util.getFormatBytes(marker.memoryUsedStart));
  }
Example #27
0
 @Override
 public void calibrate() {
   MemoryMXBean mxBean = ManagementFactory.getMemoryMXBean();
   long lastUsed = memoryUsed();
   for (int i = 0; i < 10; i++) {
     System.gc();
     System.runFinalization();
     long used = memoryUsed();
     if (mxBean.getObjectPendingFinalizationCount() == 0 && used >= lastUsed) {
       break;
     } else {
       lastUsed = used;
     }
   }
   super.calibrate();
 }
 @Override
 public long[] getMaxSystemParameters() {
   long[] systemData = new long[3];
   MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
   systemData[0] = memoryMXBean.getHeapMemoryUsage().getMax();
   systemData[1] = memoryMXBean.getNonHeapMemoryUsage().getMax();
   List<MemoryPoolMXBean> mbeans = ManagementFactory.getMemoryPoolMXBeans();
   if (mbeans != null) {
     for (MemoryPoolMXBean mbean : mbeans) {
       MemoryUsage memUsage = mbean.getUsage();
       if (mbean.getName().equals(PERMGEN_MEMORY_POOL_NAME)) {
         systemData[2] = memUsage.getMax();
       }
     }
   }
   return systemData;
 }
  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;
  }
 @Override
 public long[] getSystemStatus() {
   long[] systemData = new long[4];
   MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
   systemData[0] = memoryMXBean.getHeapMemoryUsage().getUsed();
   systemData[1] = memoryMXBean.getNonHeapMemoryUsage().getUsed();
   List<MemoryPoolMXBean> mbeans = ManagementFactory.getMemoryPoolMXBeans();
   if (mbeans != null) {
     for (MemoryPoolMXBean mbean : mbeans) {
       MemoryUsage memUsage = mbean.getUsage();
       if (mbean.getName().equals(PERMGEN_MEMORY_POOL_NAME)) {
         systemData[2] = memUsage.getUsed();
       }
     }
   }
   ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
   systemData[3] = threadMXBean.getThreadCount();
   return systemData;
 }