Example usage for java.lang.management MemoryUsage getCommitted

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

Introduction

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

Prototype

public long getCommitted() 

Source Link

Document

Returns the amount of memory in bytes that is committed for the Java virtual machine to use.

Usage

From source file:org.eclipse.gyrex.cloud.internal.NodeMetricsReporter.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }/*ww  w  . j a  va 2 s .c o  m*/

    try {
        final Properties metrics = new Properties() {
            private static final long serialVersionUID = 1L;

            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(keySet());
            }

            @Override
            public Set<Object> keySet() {
                return new TreeSet<Object>(super.keySet());
            }
        };
        final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        metrics.setProperty("os.availableProcessors",
                String.valueOf(operatingSystemMXBean.getAvailableProcessors()));
        metrics.setProperty("os.systemLoadAverage",
                String.valueOf(operatingSystemMXBean.getSystemLoadAverage()));
        metrics.setProperty("os.committedVirtualMemorySize",
                getUsingReflection(operatingSystemMXBean, "getCommittedVirtualMemorySize"));
        metrics.setProperty("os.totalSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getTotalSwapSpaceSize"));
        metrics.setProperty("os.freeSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getFreeSwapSpaceSize"));
        metrics.setProperty("os.processCpuTime",
                getUsingReflection(operatingSystemMXBean, "getProcessCpuTime"));
        metrics.setProperty("os.freePhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getFreePhysicalMemorySize"));
        metrics.setProperty("os.totalPhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getTotalPhysicalMemorySize"));
        metrics.setProperty("os.openFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getOpenFileDescriptorCount"));
        metrics.setProperty("os.maxFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getMaxFileDescriptorCount"));

        final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        metrics.setProperty("heap.used", String.valueOf(heapMemoryUsage.getUsed()));
        metrics.setProperty("heap.committed", String.valueOf(heapMemoryUsage.getCommitted()));
        metrics.setProperty("heap.max", String.valueOf(heapMemoryUsage.getMax()));
        metrics.setProperty("heap.init", String.valueOf(heapMemoryUsage.getInit()));
        final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        metrics.setProperty("nonHeap.used", String.valueOf(nonHeapMemoryUsage.getUsed()));
        metrics.setProperty("nonHeap.committed", String.valueOf(nonHeapMemoryUsage.getCommitted()));
        metrics.setProperty("nonHeap.max", String.valueOf(nonHeapMemoryUsage.getMax()));
        metrics.setProperty("nonHeap.init", String.valueOf(nonHeapMemoryUsage.getInit()));

        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        metrics.setProperty("thread.count", String.valueOf(threadMXBean.getThreadCount()));
        metrics.setProperty("thread.peak", String.valueOf(threadMXBean.getPeakThreadCount()));
        metrics.setProperty("thread.totalStarted", String.valueOf(threadMXBean.getTotalStartedThreadCount()));

        final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        metrics.setProperty("uptime", String.valueOf(runtimeMXBean.getUptime()));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final NodeInfo nodeInfo = CloudState.getNodeInfo();
        metrics.store(out, String.valueOf(nodeInfo));
        ZooKeeperGate.get().writeRecord(IZooKeeperLayout.PATH_NODES_METRICS.append(nodeInfo.getNodeId()),
                CreateMode.PERSISTENT, out.toByteArray());
        if (CloudDebug.nodeMetrics) {
            LOG.debug("Node metrics reported successfully.{}{}", SystemUtils.LINE_SEPARATOR,
                    new String(out.toByteArray(), CharEncoding.ISO_8859_1));
        }
    } catch (final Exception e) {
        LOG.warn("Failed to update node metrics. {}", e.getMessage());
    } finally {
        // reschedule
        schedule(DELAY);
    }

    return Status.OK_STATUS;
}

From source file:org.apache.hama.monitor.plugin.JvmTask.java

private void memory(final MetricsRecord record) {
    final MemoryUsage memNonHeap = memoryMXBean.getNonHeapMemoryUsage();
    final MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage();
    record.add(new Metric(MemNonHeapUsedM, memNonHeap.getUsed() / M));
    record.add(new Metric(MemNonHeapCommittedM, memNonHeap.getCommitted() / M));
    record.add(new Metric(MemHeapUsedM, memHeap.getUsed() / M));
    record.add(new Metric(MemHeapCommittedM, memHeap.getCommitted() / M));

    if (LOG.isDebugEnabled()) {
        LOG.debug(MemNonHeapUsedM.description() + ": " + memNonHeap.getUsed() / M);
        LOG.debug(MemNonHeapCommittedM.description() + ": " + memNonHeap.getCommitted() / M);
        LOG.debug(MemHeapUsedM.description() + ": " + memHeap.getUsed() / M);
        LOG.debug(MemHeapCommittedM.description() + ": " + memHeap.getCommitted() / M);
    }/* w ww . j av  a  2 s  .com*/
}

From source file:org.apache.hadoop.metrics.jvm.JvmMetrics.java

private void doMemoryUpdates() {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap = memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage();
    Runtime runtime = Runtime.getRuntime();

    metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed() / M);
    metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted() / M);
    metrics.setMetric("memHeapUsedM", memHeap.getUsed() / M);
    metrics.setMetric("memHeapCommittedM", memHeap.getCommitted() / M);
    metrics.setMetric("maxMemoryM", runtime.maxMemory() / M);
}

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  .  j ava 2s .c  o m
            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:controllers.api.core.RootApiController.java

/**
 * Return some information regarding the memory status of the instance.
 *///from   w w  w. java  2 s . co m
@ApiAuthentication(onlyRootKey = true)
public Result instanceMemoryStatus() {

    try {

        RootResponse response = new RootResponse();

        response.attributes = new HashMap<String, JsonNode>();
        List<MemoryPoolMXBean> mbeans = ManagementFactory.getMemoryPoolMXBeans();
        if (mbeans != null) {
            for (MemoryPoolMXBean mbean : mbeans) {
                System.out.println(mbean.getName());
                MemoryUsage memUsage = mbean.getUsage();
                HashMap<String, Long> memoryUsageAsMap = new HashMap<String, Long>();
                memoryUsageAsMap.put("init", memUsage.getInit());
                memoryUsageAsMap.put("max", memUsage.getMax());
                memoryUsageAsMap.put("committed", memUsage.getCommitted());
                memoryUsageAsMap.put("used", memUsage.getUsed());
                response.attributes.put(mbean.getName(), Json.toJson(memoryUsageAsMap));
            }
        }

        return getJsonSuccessResponse(response);

    } catch (Exception e) {

        return getJsonErrorResponse(new ApiError(500, "INTERNAL SERVER ERROR", e));

    }
}

From source file:org.romaframework.core.config.RomaApplicationContext.java

private void logMemoryUsage() {
    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemory = memBean.getHeapMemoryUsage();
    MemoryUsage nonHeapMemory = memBean.getNonHeapMemoryUsage();

    NumberFormat nf = NumberFormat.getInstance();
    log.info("--------------- MEMORY USAGE ---------------");
    log.info("HEAP INIT MEMORY:       " + nf.format(heapMemory.getInit()) + " bytes");
    log.info("HEAP USED MEMORY:       " + nf.format(heapMemory.getUsed()) + " bytes");
    log.info("HEAP COMMITTED MEMORY:  " + nf.format(heapMemory.getCommitted()) + " bytes");
    log.info("HEAP MAX MEMORY:        " + nf.format(heapMemory.getMax()) + " bytes");
    log.info(" ");
    log.info("NON HEAP INIT MEMORY:       " + nf.format(nonHeapMemory.getInit()) + " bytes");
    log.info("NON HEAP USED MEMORY:       " + nf.format(nonHeapMemory.getUsed()) + " bytes");
    log.info("NON HEAP COMMITTED MEMORY:  " + nf.format(nonHeapMemory.getCommitted()) + " bytes");
    log.info("NON HEAP MAX MEMORY:        " + nf.format(nonHeapMemory.getMax()) + " bytes");
    log.info("--------------------------------------------");
}

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 v  a 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:org.helios.netty.jmx.MetricCollector.java

/**
 * Generates a {@link JSONObject} representing memory usage, plus the percentage usage of:<ul>
 * <li>Memory Allocated</li>
 * <li>Memory Maximum Capacity</li>
 * </ul>/*from  w w w  .  j  a v a  2 s.c  o m*/
 * @param usage The memory usage provided by the {@link MemoryMXBean}
 * @return A {@link JSONObject} 
 * @throws JSONException I have no idea why this would be thrown
 */
protected JSONObject processMemoryUsage(MemoryUsage usage) throws JSONException {
    JSONObject json = new JSONObject(usage);
    json.put("consumed(%)", calcPercent(usage.getUsed(), usage.getCommitted()));
    json.put("capacity(%)", calcPercent(usage.getUsed(), usage.getMax()));
    return json;
}

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();/*from w w w .jav a2  s. c o  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:com.chinamobile.bcbsp.graph.GraphDataForDisk.java

/** Show the information of graph data Memory used.*/
@Override/* w  ww.j  av  a  2 s .com*/
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;
}