Example usage for java.lang.management MemoryMXBean getHeapMemoryUsage

List of usage examples for java.lang.management MemoryMXBean getHeapMemoryUsage

Introduction

In this page you can find the example usage for java.lang.management MemoryMXBean getHeapMemoryUsage.

Prototype

public MemoryUsage getHeapMemoryUsage();

Source Link

Document

Returns the current memory usage of the heap that is used for object allocation.

Usage

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

/** Run method of Thread. */
public void run() {
    while (true) {
        while (this.idle) {
            if (this.completed) {
                return;
            }//from   w w w.ja v a2  s.c om
            if (this.noMoreMessagesFlag) {
                this.superStepCounter++;
                this.noMoreMessagesFlag = false;
            }
            try {
                Thread.sleep(this.sleepTime);
            } catch (InterruptedException e) {
                LOG.error("[RPCSingleSendSlave] to " + this.hostNameAndPort + " has been interrupted for ", e);
                return;
            }
        }
        if (this.hostNameAndPort == null) {
            LOG.error("Destination hostname is null.");
            return;
        }
        if (this.messageQueue == null) {
            LOG.error("Message queue for ProducerTool is null.");
            return;
        }
        this.messageCount = 0;
        this.connectTime = 0;
        this.sendTime = 0;
        while (true) {
            if (this.reconnectCount == RPCSingleSendSlave.RECONNECTTHRESHOLD) {
                break;
            }
            try {
                if (this.newHostNameAndPort) { // Should create new connection
                    if (senderProtocol != null) {
                        LOG.info("Sender RPC protocol is not null.");
                    } else {
                        LOG.info("Sender RPC protocol is null and it will instanced now.");
                    }
                    long start = System.currentTimeMillis();
                    String[] tmp = this.hostNameAndPort.split(":");
                    String hostname = tmp[0];
                    int portNum = Integer.parseInt(tmp[1]);
                    this.senderProtocol = (RPCCommunicationProtocol) RPC.waitForProxy(
                            RPCCommunicationProtocol.class, RPCCommunicationProtocol.protocolVersion,
                            new InetSocketAddress(hostname, portNum), new Configuration());
                    this.connectTime += (System.currentTimeMillis() - start);
                    this.newHostNameAndPort = false;
                }
                // Start sending messages
                this.sendPacked();
                this.idle = true;
                break;
            } catch (Exception e) {
                this.reconnectCount++;
                if (this.reconnectCount == 1) {
                    LOG.error("[SingRPCSendSlave] to " + this.hostNameAndPort + " caught: ", e);
                }
                LOG.info("[SingRPCSendSlave] to " + this.hostNameAndPort + " is reconnecting for "
                        + this.reconnectCount + "th time.");
                LOG.info("---------------- Memory Info ------------------");
                MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
                MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
                long used = memoryUsage.getUsed();
                long committed = memoryUsage.getCommitted();
                LOG.info("[JVM Memory used] = " + used / MB_SIZE + "MB");
                LOG.info("[JVM Memory committed] = " + committed / MB_SIZE + "MB");
                LOG.info("-----------------------------------------------");
                try {
                    Thread.sleep(this.sleepTime);
                } catch (InterruptedException e1) {
                    LOG.error("[SingRPCSendSlave] caught: ", e1);
                }
            }
        }
        LOG.info("[SingRPCSendSlave] to " + this.hostNameAndPort + " has sent " + this.messageCount
                + " messages totally! (with " + this.messageQueue.size() + " messages lost!)");
        this.sender.addConnectTime(this.connectTime);
        /* Clock */
        this.sender.addSendTime(this.sendTime);
        if (this.reconnectCount == RPCSingleSendSlave.RECONNECTTHRESHOLD) {
            LOG.info("[ProducerTool] to " + this.hostNameAndPort + " has reconnected for " + this.reconnectCount
                    + " times but failed!");
            this.isFailed = true;
            break;
        }
    }
}

From source file:com.springsource.hq.plugin.tcserver.plugin.TomcatMeasurementPlugin.java

private long getFreeHeapMemory(MBeanServerConnection connection) throws MetricUnreachableException {
    try {/*from  w  w w  .  ja  va  2s.c om*/
        MemoryMXBean memoryBean = ManagementFactory.newPlatformMXBeanProxy(connection, "java.lang:type=Memory",
                MemoryMXBean.class);
        long max = memoryBean.getHeapMemoryUsage().getMax();
        long used = memoryBean.getHeapMemoryUsage().getUsed();
        return max - used;
    } catch (IOException e) {
        throw new MetricUnreachableException("Error retrieving Memory MBean" + e.getMessage(), e);
    }
}

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

/** Run method of Thread. */
public final void run() {
    while (true) {
        while (this.idle) {
            if (this.completed) {
                return;
            }//from w w w.  j  a  va 2 s  .c o m
            if (this.noMoreMessagesFlag) {
                this.superStepCounter++;
                this.noMoreMessagesFlag = false;
                // LOG.info("Test Progress: from " + (this.superStepCounter - 1) +
                // " to " + this.superStepCounter);
            }
            try {
                Thread.sleep(this.sleepTime);
            } catch (InterruptedException e) {
                LOG.error("[ProducerTool] to " + this.hostNameAndPort + " has been interrupted for ", e);
                return;
            }
        }
        if (this.hostNameAndPort == null) {
            LOG.error("Destination hostname is null.");
            return;
        }
        if (this.messageQueue == null) {
            LOG.error("Message queue for ProducerTool is null.");
            return;
        }
        this.messageCount = 0;
        this.connectTime = 0;
        this.sendTime = 0;
        while (true) {
            if (this.reconnectCount == ProducerTool.RECONNECTTHRESHOLD) {
                break;
            }
            try {
                if (this.newHostNameAndPort) { // Should create new connection.
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (Throwable ignore) {
                            LOG.warn("[ConsumerTool] run connection " + ignore);
                        }
                    }
                    long start = System.currentTimeMillis();
                    /** Clock */
                    // Make the destination broker's url.
                    this.url = "tcp://" + this.hostNameAndPort;
                    // Create the connection.
                    // ActiveMQConnectionFactory connectionFactory = new
                    // ActiveMQConnectionFactory(
                    // user, password, url);
                    BSPActiveMQConnFactory connectionFactory = new BSPActiveMQConnFactoryImpl();
                    connectionFactory.activeMQConnFactoryMethod(url);
                    connectionFactory.setCopyMessageOnSend(false);
                    connection = connectionFactory.createConnection();
                    connection.start();
                    // Create the session
                    session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
                    this.connectTime += (System.currentTimeMillis() - start);
                    /* Clock */
                    this.newHostNameAndPort = false;
                    start = System.currentTimeMillis();
                    /* Clock */
                    destination = session.createQueue(subject);
                    // Create the producer.
                    producer = session.createProducer(destination);
                    if (persistent) {
                        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                    } else {
                        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                    }
                    if (timeToLive != 0) {
                        producer.setTimeToLive(timeToLive);
                    }
                    this.connectTime += (System.currentTimeMillis() - start);
                }
                // Start sending messages
                sendLoopOptimistic(session, producer);
                this.idle = true;
                break;
            } catch (Exception e) {
                this.reconnectCount++;
                if (this.reconnectCount == 1) {
                    LOG.error("[ProducerTool] to " + this.hostNameAndPort + " caught: ", e);
                }
                LOG.info("[ProducerTool] to " + this.hostNameAndPort + " is reconnecting for "
                        + this.reconnectCount + "th time.");
                LOG.info("---------------- Memory Info ------------------");
                MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
                MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
                long used = memoryUsage.getUsed();
                long committed = memoryUsage.getCommitted();
                LOG.info("[JVM Memory used] = " + used / MB_SIZE + "MB");
                LOG.info("[JVM Memory committed] = " + committed / MB_SIZE + "MB");
                LOG.info("-----------------------------------------------");
                try {
                    Thread.sleep(this.sleepTime);
                } catch (InterruptedException e1) {
                    LOG.error("[ProducerTool] caught: ", e1);
                }
            }
        }
        LOG.info("[ProducerTool] to " + this.hostNameAndPort + " has sent " + this.messageCount
                + " messages totally! (with " + this.messageQueue.size() + " messages lost!)");
        this.sender.addConnectTime(this.connectTime);
        /* Clock */
        this.sender.addSendTime(this.sendTime);
        /* Clock */
        if (this.reconnectCount == ProducerTool.RECONNECTTHRESHOLD) {
            LOG.info("[ProducerTool] to " + this.hostNameAndPort + " has reconnected for " + this.reconnectCount
                    + " times but failed!");
            this.isFailed = true;
            break;
        }
    }
}

From source file:com.knowbout.cc2nlp.server.CCEventServiceImpl.java

private void checkStats() {
    long timestamp = new Date().getTime();
    String day = getFileDate(timestamp);
    if (!day.equals(currentDay)) {
        if (statsFile != null) {
            statsFile.println("</table></body></html>");
            statsFile.close();//  w  w  w  . j  av  a 2 s.  co  m
            statsFile = null;
        }
        currentDay = day;
    }
    if (hostname == null) {
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            hostname = "UnknownHost";
        }
    }
    String dirname = documentRoot + "/stats/" + currentDay + "/" + hostname;
    String statsFileName = dirname + "/nlpprocstats.html";
    int interval = 5; // minutes
    try {
        if (statsFile == null) {
            File dir = new File(dirname);
            if ((!dir.exists()) && (!dir.mkdirs())) {
                throw new IOException("Error creating directory " + dirname);
            }
            File file = new File(statsFileName);
            if (file.exists()) {
                statsFile = new PrintStream(new FileOutputStream(statsFileName, true));
                statsFile.println("<tr><td colspan='5'>Restart</td></tr>");
            } else {
                statsFile = new PrintStream(new FileOutputStream(statsFileName));
                String title = "NLP Process (tomcat) status for " + currentDay;
                statsFile.println("<html><head><title>" + title + "</title></head>");
                statsFile.println("<body><h1>" + title + "</h1>");
                statsFile.println("<table border='1'>");
                statsFile.println("<tr>");
                statsFile.println(
                        "<th colspan='2'>" + interval + " Minute Intervals</th><th colspan='3'>Memory</th>");
                statsFile.println("</tr>");
                statsFile.println("<tr>");
                statsFile.println("<th>Timestamp</th>");
                statsFile.println("<th>Time</th>");
                statsFile.println("<th>Used</th>");
                statsFile.println("<th>Committed</th>");
                statsFile.println("<th>Max<th>");
                statsFile.println("</tr>");
            }
        }
        if ((timestamp - lastWrite) > (interval * 60 * 1000)) {
            lastWrite = timestamp;
            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(TimeZone.getTimeZone("GMT"));
            cal.setTimeInMillis(timestamp);
            String time = String.format("%1$tH:%1$tM:%1$tS", cal);
            MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
            MemoryUsage memory = memoryBean.getHeapMemoryUsage();
            statsFile.print("<tr>");
            statsFile.print("<td>" + timestamp + "</td>");
            statsFile.print("<td>" + time + "</td>");
            statsFile.format("<td>%,d</td>", memory.getUsed());
            statsFile.format("<td>%,d</td>", memory.getCommitted());
            statsFile.format("<td>%,d</td>", memory.getMax());
            statsFile.println("</tr>");
        }
    } catch (IOException e) {
        log.error("Error opening or writing to " + statsFileName, e);
    }
}

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

/**
 * Renders tools page./*from  w  w w  . ja  va2  s. com*/
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    Bundle[] bundles = BundleContextHolder.getInstance().getBundleContext().getBundles();
    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    TemplateEngines.getDefault().render(TemplateContext.builder().request(req).response(resp)
            .template(TOOLS_TEMPLATE).locale(req.getLocale())
            .contextObject(ContextObject.newContextObject().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(memoryMXBean.getHeapMemoryUsage().getMax()))
                    .put("usedMemory",
                            FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getUsed()))
                    .put("processors", Runtime.getRuntime().availableProcessors()))
            .build());
}

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;/*ww w.j  a va  2s .c  om*/
    }

    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/*from ww  w. ja v a  2 s.  c  om*/
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.chinamobile.bcbsp.graph.GraphDataForDisk.java

/**
 * Initialize the graph data disk manager with job and partitionID. Get the
 * parameter of graph on disk./*from  ww w . j a  v a 2s. c om*/
 * @param job
 * @param partitionID
 */
public void initialize(BSPJob job, int partitionID) {
    vertexClass = job.getVertexClass();
    edgeClass = job.getEdgeClass();
    LOG.info("========== Initializing Graph Data For Disk ==========");
    this.dataPercent = job.getMemoryDataPercent(); // Default 0.8
    this.jobID = job.getJobID();
    this.partitionID = partitionID;
    this.beta = job.getBeta();
    this.hashBucketNumber = job.getHashBucketNumber();
    LOG.info("[beta] = " + this.beta);
    LOG.info("[hashBucketNumber] = " + this.hashBucketNumber);
    this.hashBuckets = new ArrayList<ArrayList<Vertex>>(hashBucketNumber);
    // So the bitmaps's length decides the maximum nodes of a bucket is
    // 320*32.
    this.bitmaps = new ArrayList<ArrayList<Integer>>(hashBucketNumber);
    this.metaTable = new ArrayList<BucketMeta>(hashBucketNumber);
    // Initialize the meta table and bitmaps.
    for (int i = 0; i < hashBucketNumber; i++) {
        this.hashBuckets.add(null);
        // init the meta table.
        BucketMeta meta = new BucketMeta();
        meta.superStepCount = -1;
        meta.onDiskFlag = false;
        meta.length = 0;
        meta.lengthInMemory = 0;
        meta.count = 0;
        meta.activeCount = 0;
        metaTable.add(meta);
        // init the bitmapsCache.
        ArrayList<Integer> bitmap = new ArrayList<Integer>(Constants.GRAPH_BITMAP_BUCKET_NUM_BYTES);
        for (int j = 0; j < Constants.GRAPH_BITMAP_BUCKET_NUM_BYTES; j++) {
            bitmap.add(0);
        }
        this.bitmaps.add(bitmap);
    }
    // Initialize the size of objects and data structures.
    //int sizeOfMetaBucket = sizer.sizeOf(new BucketMeta());
    //this.sizeOfMetaTable = (sizeOfMetaBucket + sizeOfRef) * hashBucketNumber;
    int sizeOfBitmap = sizer.sizeOf(new ArrayList<Integer>());
    this.sizeOfBitmapsInMem = (sizeOfBitmap + sizeOfRef) * hashBucketNumber;
    Vertex<?, ?, ?> tmpVertex = null;
    Edge<?, ?> tmpEdge = null;
    try {
        tmpVertex = this.vertexClass.newInstance();
        tmpEdge = this.edgeClass.newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException("[GraphDataForDisk] caught:", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("[GraphDataForDisk] caught:", e);
    }
    this.sizeOfVertex = sizer.sizeOf(tmpVertex);
    this.sizeOfEdge = sizer.sizeOf(tmpEdge);
    LOG.info("[Default initial size of Vertex] = " + this.sizeOfVertex + "B");
    LOG.info("[Default initial size of Edge] = " + this.sizeOfEdge + "B");
    // Get the memory mxBean.
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    // Get the heap memory usage.
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
    long maxHeapSize = memoryUsage.getMax();
    LOG.info("[JVM max Heap size] = " + maxHeapSize / MB_SIZE + "MB");
    this.sizeOfGraphSpace = (long) (maxHeapSize * dataPercent * beta);
    this.sizeThreshold = (sizeOfGraphSpace);
    this.sizeOfGraphDataInMem = 0;
    this.sizeForAll = 0;
    this.totalSizeOfVertex = 0;
    this.totalCountOfVertex = 0;
    this.totalSizeOfEdge = 0;
    this.totalCountOfEdge = 0;
    this.sortedBucketIndexList = new int[hashBucketNumber];
    this.fileRoot = new File("/tmp/bcbsp/" + this.jobID.toString() + "/" + "partition-" + this.partitionID);
    this.graphDataFile = new File(this.fileRoot + "/" + "GraphData");
    LOG.info("[size of Graph Data Space] = " + this.sizeOfGraphSpace / MB_SIZE + "MB");
    LOG.info("[threshold of Graph Data] = " + this.sizeThreshold / MB_SIZE + "MB");
    LOG.info("======================================================");
}

From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java

@GET
@RequireAdmin//from w  w w.j  a  va 2 s . c  o  m
@APIDescription("Gets the application system status")
@Produces({ MediaType.APPLICATION_JSON })
@DataType(ApplicationStatus.class)
@Path("/status")
public Response getApplicationStatus() {
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    ApplicationStatus applicationStatus = new ApplicationStatus();
    applicationStatus.setApplicationVersion(PropertiesManager.getApplicationVersion());
    applicationStatus.setProcessorCount(operatingSystemMXBean.getAvailableProcessors());
    applicationStatus.setSystemLoad(operatingSystemMXBean.getSystemLoadAverage());
    applicationStatus.setSystemProperties(runtimeMXBean.getSystemProperties());

    applicationStatus.getHeapMemoryStatus().setName("Heap");
    applicationStatus.getHeapMemoryStatus().setDetails(memoryMXBean.getHeapMemoryUsage().toString());
    applicationStatus.getHeapMemoryStatus()
            .setInitKb(memoryMXBean.getHeapMemoryUsage().getInit() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getInit() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setUsedKb(memoryMXBean.getHeapMemoryUsage().getUsed() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getUsed() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setMaxKb(memoryMXBean.getHeapMemoryUsage().getMax() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getMax() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setCommitedKb(memoryMXBean.getHeapMemoryUsage().getCommitted() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getCommitted() / 1024
                    : 0);

    applicationStatus.getNonHeapMemoryStatus().setName("Non-Heap");
    applicationStatus.getNonHeapMemoryStatus().setDetails(memoryMXBean.getNonHeapMemoryUsage().toString());
    applicationStatus.getNonHeapMemoryStatus()
            .setInitKb(memoryMXBean.getNonHeapMemoryUsage().getInit() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getInit() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setUsedKb(memoryMXBean.getNonHeapMemoryUsage().getUsed() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getUsed() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setMaxKb(memoryMXBean.getNonHeapMemoryUsage().getMax() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getMax() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setCommitedKb(memoryMXBean.getNonHeapMemoryUsage().getCommitted() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getCommitted() / 1024
                    : 0);

    applicationStatus.setLiveThreadCount(threadMXBean.getThreadCount());
    applicationStatus.setTotalThreadCount(threadMXBean.getTotalStartedThreadCount());

    applicationStatus.setStartTime(new Date(runtimeMXBean.getStartTime()));
    applicationStatus.setUpTime(TimeUtil.millisToString(runtimeMXBean.getUptime()));

    for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        applicationStatus.getGarbageCollectionInfos()
                .add(TimeUtil.millisToString(garbageCollectorMXBean.getCollectionTime()) + " - ("
                        + garbageCollectorMXBean.getCollectionCount() + ")");
    }

    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        MemoryPoolStatus memoryPoolStatus = new MemoryPoolStatus();
        memoryPoolStatus.setName(memoryPoolMXBean.getName() + " - " + memoryPoolMXBean.getType());
        memoryPoolStatus.setDetails(memoryPoolMXBean.getUsage().toString());
        memoryPoolStatus.setInitKb(
                memoryPoolMXBean.getUsage().getInit() != 0 ? memoryPoolMXBean.getUsage().getInit() / 1024 : 0);
        memoryPoolStatus.setUsedKb(
                memoryPoolMXBean.getUsage().getUsed() != 0 ? memoryPoolMXBean.getUsage().getUsed() / 1024 : 0);
        memoryPoolStatus.setMaxKb(
                memoryPoolMXBean.getUsage().getMax() != 0 ? memoryPoolMXBean.getUsage().getMax() / 1024 : 0);
        memoryPoolStatus.setCommitedKb(memoryPoolMXBean.getUsage().getCommitted() != 0
                ? memoryPoolMXBean.getUsage().getCommitted() / 1024
                : 0);

        applicationStatus.getMemoryPools().add(memoryPoolStatus);
    }

    return sendSingleEntityResponse(applicationStatus);
}

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 .  jav  a 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();
}