Example usage for java.lang.management MemoryUsage getUsed

List of usage examples for java.lang.management MemoryUsage getUsed

Introduction

In this page you can find the example usage for java.lang.management MemoryUsage getUsed.

Prototype

public long getUsed() 

Source Link

Document

Returns the amount of used memory in bytes.

Usage

From source file:com.alibaba.jstorm.daemon.nimbus.TopologyMetricsRunnable.java

public TopologyMetricsRunnable(final NimbusData nimbusData) {
    setName(getClass().getSimpleName());

    this.nimbusData = nimbusData;

    this.localMode = nimbusData.isLocalMode();
    if (localMode) {
        this.metricStat = new AtomicIntegerArray(1);
        return;/*from w ww . j  a  va2s  . c o  m*/
    }

    LOG.info("create topology metrics runnable.");
    this.metricCache = nimbusData.getMetricCache();
    this.stormClusterState = nimbusData.getStormClusterState();
    this.isShutdown = nimbusData.getIsShutdown();

    clusterName = ConfigExtension.getClusterName(nimbusData.getConf());
    if (clusterName == null) {
        throw new RuntimeException("cluster.name property must be set in storm.yaml!");
    }

    this.maxPendingUploadMetrics = ConfigExtension.getMaxPendingMetricNum(nimbusData.getConf());
    this.metricStat = new AtomicIntegerArray(this.maxPendingUploadMetrics);

    int cnt = 0;
    for (int i = 0; i < maxPendingUploadMetrics; i++) {
        TopologyMetricDataInfo obj = getMetricDataInfoFromCache(i);
        if (obj != null) {
            this.metricStat.set(i, SET);
            cnt++;
        }
    }
    LOG.info("pending upload metrics: {}", cnt);

    // init alive topologies from zk
    this.refreshTopologies();
    this.refreshTopologiesThread = new AsyncLoopThread(new RefreshTopologiesThread());

    this.clusterMetricsUpdateExecutor = Executors.newSingleThreadScheduledExecutor();
    this.clusterMetricsUpdateExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            int secOffset = TimeUtils.secOffset();
            int offset = 55;
            if (secOffset < offset) {
                JStormUtils.sleepMs((offset - secOffset) * 1000);
            } else if (secOffset == offset) {
                // do nothing
            } else {
                JStormUtils.sleepMs((60 - secOffset + offset) * 1000);
            }

            LOG.info("cluster metrics force upload.");
            mergeAndUploadClusterMetrics();
        }
    }, 5, 60, TimeUnit.SECONDS);

    // track nimbus JVM heap
    JStormMetrics.registerWorkerGauge(JStormMetrics.NIMBUS_METRIC_KEY, MetricDef.MEMORY_USED,
            new AsmGauge(new Gauge<Double>() {
                @Override
                public Double getValue() {
                    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
                    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
                    return (double) memoryUsage.getUsed();
                }
            }));
}

From source file:com.chinamobile.bcbsp.graph.GraphDataForDisk.java

/** Show the information of graph data Memory used.*/
@Override//www  .  j a v  a  2  s  .  c  o  m
public void showMemoryInfo() {
    LOG.info("----------------- Memory Info of Graph -----------------");
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
    long used = memoryUsage.getUsed();
    long committed = memoryUsage.getCommitted();
    LOG.info("<Real> [Memory used] = " + used / MB_SIZE + "MB");
    LOG.info("<Real> [Memory committed] = " + committed / MB_SIZE + "MB");
    LOG.info("<Evaluate> [size of Vertex] = " + this.sizeOfVertex + "B");
    LOG.info("<Evaluate> [total size of Vertex] = " + this.totalSizeOfVertex / MB_SIZE + "MB");
    LOG.info("<Evaluate> [total count of Vertex] = " + this.totalCountOfVertex);
    LOG.info("<Evaluate> [total count of Edge] = " + this.totalCountOfEdge);
    LOG.info("<Evaluate> [size fo MetaTable In Memory] = " + this.sizeOfMetaTable / KB_SIZE + "KB");
    LOG.info("<Evaluate> [size of Graph Data In Memory] = " + this.sizeOfGraphDataInMem / MB_SIZE + "MB");
    LOG.info("<Evaluate> [size fo Bitmaps In Memory] = " + this.sizeOfBitmapsInMem / KB_SIZE + "KB");
    LOG.info("<Evaluate> [size of Graph Data Threshold] = " + this.sizeThreshold / MB_SIZE + "MB");
    LOG.info("----------------- -------------------- -----------------");
    //    this.showHashBucketsInfo();
    LOG.info("[==>Clock<==] <GraphDataForDisk: save bucket> totally used " + this.writeDiskTime / 1000f
            + " seconds");
    LOG.info("[==>Clock<==] <GraphDataForDisk: load bucket> totally used " + this.readDiskTime / 1000f
            + " seconds");
    LOG.info("[==>Clock<==] <GraphDataForDisk: Disk I/O> totally used "
            + (this.writeDiskTime + this.readDiskTime) / 1000f + " seconds");
    this.writeDiskTime = 0;
    this.readDiskTime = 0;
}

From source file:com.adeptj.runtime.servlet.ToolsServlet.java

/**
 * Renders tools page./*from w  w w.  j  ava  2s . c o  m*/
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    Bundle[] bundles = BundleContextHolder.getInstance().getBundleContext().getBundles();
    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    TemplateEngine.getInstance()
            .render(TemplateContext.builder().request(req).response(resp).template(TOOLS_TEMPLATE)
                    .locale(req.getLocale())
                    .templateData(TemplateData.newTemplateData().put("username", req.getRemoteUser())
                            .put("sysProps", System.getProperties().entrySet())
                            .put("totalBundles", bundles.length).put("bundles", bundles)
                            .put("runtime", JAVA_RUNTIME_NAME + "(build " + JAVA_RUNTIME_VERSION + ")")
                            .put("jvm", JAVA_VM_NAME + "(build " + JAVA_VM_VERSION + ", " + JAVA_VM_INFO + ")")
                            .put("startTime", Date.from(Instant.ofEpochMilli(startTime)))
                            .put("upTime", Times.format(startTime))
                            .put("maxMemory", FileUtils.byteCountToDisplaySize(memoryUsage.getMax()))
                            .put("usedMemory", FileUtils.byteCountToDisplaySize(memoryUsage.getUsed()))
                            .put("processors", Runtime.getRuntime().availableProcessors()))
                    .build());
}

From source file:com.chinamobile.bcbsp.comm.MessageQueuesForDisk.java

/** Show the information of Memory. */
public void showMemoryInfo() {
    LOG.info("---------------- Memory Info for Messages ------------------");
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
    long used = memoryUsage.getUsed();
    long committed = memoryUsage.getCommitted();
    LOG.info("<Real> [Memory used] = " + used / MB_SIZE + "MB");
    LOG.info("<Real> [Memory committed] = " + committed / MB_SIZE + "MB");
    LOG.info("<Evaluate> [size of Message] = " + this.sizeOfMessage + "B");
    LOG.info("<Evaluate> [size of Messages Data In Memory] = " + this.sizeOfMessagesDataInMem / MB_SIZE + "MB");
    LOG.info("<Evaluate> [size of HashMaps In Memory] = " + this.sizeOfHashMapsInMem / MB_SIZE + "MB");
    LOG.info("<Evaluate> [size of Messages Data Threshold] = " + this.sizeThreshold / MB_SIZE + "MB");
    LOG.info(/* w w w.  ja  va 2  s  .co  m*/
            "<Evaluate> [count of Messages Data In Memory] = " + this.countOfMessagesDataInMem / KB_SIZE + "K");
    LOG.info("<Evaluate> [count of Messages Data Threshold] = " + this.countThreshold / KB_SIZE + "K");
    LOG.info("----------------- ------------------------ -----------------");
    // showHashBucketsInfo();
}

From source file:com.eurelis.opencms.admin.systeminformation.CmsMemoryOverviewDialog.java

/**
 * Initializes the infos object.<p>
 *///from ww  w . j a v a 2s .co  m
protected void initInfosObject() {

    com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    java.lang.management.OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    java.lang.management.ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    java.lang.management.RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    java.lang.management.ClassLoadingMXBean classesBean = ManagementFactory.getClassLoadingMXBean();

    for (java.lang.management.MemoryPoolMXBean item : ManagementFactory.getMemoryPoolMXBeans()) {
        java.lang.management.MemoryUsage mu = item.getUsage();
        String name = item.getName();

        if (name.toLowerCase().contains("perm")) {
            setMemPermMax("" + mu.getMax());
            setMemPermTotal("" + mu.getCommitted());
            setMemPermUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("old")) {
            setMemOldMax("" + mu.getMax());
            setMemOldTotal("" + mu.getCommitted());
            setMemOldUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("eden")) {
            setMemEdenMax("" + mu.getMax());
            setMemEdenTotal("" + mu.getCommitted());
            setMemEdenUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("survivor")) {
            setMemSurvivorMax("" + mu.getMax());
            setMemSurvivorTotal("" + mu.getCommitted());
            setMemSurvivorUsed("" + mu.getUsed());
        } else {
            //LOG.debug("MemoryPoolMXBean name = " + name.toLowerCase());
        }
    }

    Object o;
    if (CmsStringUtil.isEmpty(getParamAction())) {
        o = new CmsAdminSettings(getSession());
    } else {
        // this is not the initial call, get the job object from session
        o = getDialogObject();
    }
    if (!(o instanceof CmsAdminSettings)) {
        // create a new history settings handler object
        m_adminSettings = new CmsAdminSettings(getSession());
    } else {
        // reuse html import handler object stored in session
        m_adminSettings = (CmsAdminSettings) o;
    }

    setParamCloseLink(getJsp()
            .link("/system/workplace/views/admin/admin-main.jsp?path=/eurelis_system_information/memory.jsp"));
}

From source file:org.kuali.test.runner.execution.TestExecutionContext.java

private String getValueFromMXBeanObject(String name, PlatformManagedObject mxbean) {
    String retval = null;/*from   www .  j av a2  s  .c om*/

    try {
        Method m = mxbean.getClass().getMethod("get" + name, new Class[0]);

        if (m != null) {
            Object o = m.invoke(mxbean);

            if (o != null) {
                if (o instanceof MemoryUsage) {
                    MemoryUsage mu = (MemoryUsage) o;
                    retval = "" + mu.getUsed();
                } else {
                    retval = o.toString();
                }
            }
        }
    }

    catch (Exception ex) {
    }
    ;

    return retval;
}

From source file:org.apache.flink.runtime.taskmanager.TaskManager.java

private String getMemoryUsageStatsAsString(MemoryMXBean memoryMXBean) {
    MemoryUsage heap = memoryMXBean.getHeapMemoryUsage();
    MemoryUsage nonHeap = memoryMXBean.getNonHeapMemoryUsage();

    int mb = 20;/* w ww.ja  v  a2  s  .c  o m*/

    long heapUsed = heap.getUsed() >> mb;
    long heapCommitted = heap.getCommitted() >> mb;
    long heapMax = heap.getMax() >> mb;

    long nonHeapUsed = nonHeap.getUsed() >> mb;
    long nonHeapCommitted = nonHeap.getCommitted() >> mb;
    long nonHeapMax = 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;
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.JvmMemoryUsageMetricSet.java

JvmMemoryUsageMetricSet(final MemoryUsageProvider memoryUsageProvider) {
    Preconditions.checkNotNull(memoryUsageProvider);

    final MemoryUsage memoryUsage = memoryUsageProvider.get();
    Preconditions.checkNotNull(memoryUsage);

    Map<String, Metric> metricsByNames = new HashMap<>();

    if (memoryUsage.getInit() >= 0) {
        this.initialSizeInBytesGauge = new Gauge<Long>() {
            @Override/*from  ww w . j  a  v  a  2  s  .  c o m*/
            public Long getValue() {
                return memoryUsageProvider.get().getInit();
            }
        };
        metricsByNames.put("initialInBytes", initialSizeInBytesGauge);
    }

    this.usedMemoryInBytesGauge = new Gauge<Long>() {
        @Override
        public Long getValue() {
            return memoryUsageProvider.get().getUsed();
        }
    };
    metricsByNames.put("usedInBytes", usedMemoryInBytesGauge);

    if (memoryUsage.getMax() >= 0) {
        this.maxAvailableMemoryInBytesGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return memoryUsageProvider.get().getMax();
            }
        };
        metricsByNames.put("maxAvailableInBytes", maxAvailableMemoryInBytesGauge);
    }

    this.committedMemoryInBytesGauge = new Gauge<Long>() {
        @Override
        public Long getValue() {
            return memoryUsageProvider.get().getCommitted();
        }
    };
    metricsByNames.put("committedInBytes", committedMemoryInBytesGauge);

    this.usedMemoryPercentageGauge = new Gauge<Double>() {
        @Override
        public Double getValue() {
            MemoryUsage memoryUsage = memoryUsageProvider.get();
            long max = memoryUsage.getMax() > 0 ? memoryUsage.getMax() : memoryUsage.getCommitted();
            return Double.valueOf(memoryUsage.getUsed()) / max * 100;
        }
    };
    metricsByNames.put("usedPercentage", usedMemoryPercentageGauge);

    this.metricsByNames = metricsByNames;
}

From source file:org.apache.hadoop.hbase.regionserver.HRegionServer.java

ClusterStatusProtos.ServerLoad buildServerLoad(long reportStartTime, long reportEndTime) {
    // We're getting the MetricsRegionServerWrapper here because the wrapper computes requests
    // per second, and other metrics  As long as metrics are part of ServerLoad it's best to use
    // the wrapper to compute those numbers in one place.
    // In the long term most of these should be moved off of ServerLoad and the heart beat.
    // Instead they should be stored in an HBase table so that external visibility into HBase is
    // improved; Additionally the load balancer will be able to take advantage of a more complete
    // history.//from   w w  w . j ava2s. c om
    MetricsRegionServerWrapper regionServerWrapper = this.metricsRegionServer.getRegionServerWrapper();
    Collection<HRegion> regions = getOnlineRegionsLocalContext();
    MemoryUsage memory = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

    ClusterStatusProtos.ServerLoad.Builder serverLoad = ClusterStatusProtos.ServerLoad.newBuilder();
    serverLoad.setNumberOfRequests((int) regionServerWrapper.getRequestsPerSecond());
    serverLoad.setTotalNumberOfRequests((int) regionServerWrapper.getTotalRequestCount());
    serverLoad.setUsedHeapMB((int) (memory.getUsed() / 1024 / 1024));
    serverLoad.setMaxHeapMB((int) (memory.getMax() / 1024 / 1024));
    Set<String> coprocessors = this.hlog.getCoprocessorHost().getCoprocessors();
    for (String coprocessor : coprocessors) {
        serverLoad.addCoprocessors(Coprocessor.newBuilder().setName(coprocessor).build());
    }
    RegionLoad.Builder regionLoadBldr = RegionLoad.newBuilder();
    RegionSpecifier.Builder regionSpecifier = RegionSpecifier.newBuilder();
    for (HRegion region : regions) {
        serverLoad.addRegionLoads(createRegionLoad(region, regionLoadBldr, regionSpecifier));
    }
    serverLoad.setReportStartTime(reportStartTime);
    serverLoad.setReportEndTime(reportEndTime);
    if (this.infoServer != null) {
        serverLoad.setInfoServerPort(this.infoServer.getPort());
    } else {
        serverLoad.setInfoServerPort(-1);
    }
    return serverLoad.build();
}