Example usage for java.lang.management ManagementFactory getMemoryMXBean

List of usage examples for java.lang.management ManagementFactory getMemoryMXBean

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getMemoryMXBean.

Prototype

public static MemoryMXBean getMemoryMXBean() 

Source Link

Document

Returns the managed bean for the memory system of the Java virtual machine.

Usage

From source file:com.alibaba.jstorm.utils.JStormUtils.java

public static Double getMemUsage() {
    if (OSInfo.isLinux() == true) {
        try {//from  w w  w  .  j a va  2  s  .c  o m
            Double value = 0.0;
            String pid = JStormUtils.process_pid();
            String command = String.format("top -b -n 1 -p %s | grep -w %s", pid, pid);
            String output = SystemOperation.exec(command);

            int m = 0;
            String[] strArray = output.split(" ");
            for (int i = 0; i < strArray.length; i++) {
                String info = strArray[i];
                if (info.trim().length() == 0) {
                    continue;
                }
                if (m == 5) {
                    // memory
                    String unit = info.substring(info.length() - 1);

                    if (unit.equalsIgnoreCase("g")) {
                        value = Double.parseDouble(info.substring(0, info.length() - 1));
                        value *= 1000000000;
                    } else if (unit.equalsIgnoreCase("m")) {
                        value = Double.parseDouble(info.substring(0, info.length() - 1));
                        value *= 1000000;
                    } else {
                        value = Double.parseDouble(info);
                    }

                    //LOG.info("!!!! Get Memory Size:{}, info:{}", value, info);
                    return value;
                }
                if (m == 8) {
                    // cpu usage

                }
                if (m == 9) {
                    // memory ratio

                }
                m++;
            }
        } catch (Exception e) {
            LOG.warn("Failed to get memory usage .");

        }
    }

    // this will be incorrect
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();

    return Double.valueOf(memoryUsage.getUsed());
}

From source file:com.appeligo.captions.CaptionListener.java

private synchronized static void checkStats() {
    int interval = 5; // minutes
    long timestamp = new Date().getTime();
    if ((timestamp - lastWrite) > (interval * 60 * 1000)) {
        lastWrite = timestamp;/*from  w w w. j  av  a  2  s. co m*/
        String day = Utils.getDatePath(timestamp);
        if (!day.equals(currentDay)) {
            if (statsFile != null) {
                statsFile.println("</table></body></html>");
                statsFile.close();
                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 + "/searchprocstats.html";
        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 = "Search 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'>Mem Pre GC</th>" + "<th>GC</th>"
                            + "<th colspan='3'>Mem Post GC</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("<th>Millis</th>");
                    statsFile.println("<th>Used</th>");
                    statsFile.println("<th>Committed</th>");
                    statsFile.println("<th>Max</th>");
                    statsFile.println("</tr>");
                }
            }
            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());
            long beforeGC = System.currentTimeMillis();
            System.gc();
            long elapsed = System.currentTimeMillis() - beforeGC;
            statsFile.format("<td>%,d</td>", (int) elapsed);
            memoryBean = ManagementFactory.getMemoryMXBean();
            memory = memoryBean.getHeapMemoryUsage();
            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.all.ultrapeer.UltrapeerMonitor.java

private double getHeapUsage() {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
    return ((double) heapMemoryUsage.getUsed()) / ((double) heapMemoryUsage.getMax()) * 100.0;
}

From source file:com.blm.orc.WriterImpl.java

private long getMemoryAvailableForORC() {
    HiveConf.ConfVars poolVar = HiveConf.ConfVars.HIVE_ORC_FILE_MEMORY_POOL;
    double maxLoad = conf.getFloat(poolVar.varname, poolVar.defaultFloatVal);
    long totalMemoryPool = Math
            .round(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax() * maxLoad);
    return totalMemoryPool;
}

From source file:com.koda.integ.hbase.blockcache.OffHeapBlockCache.java

/**
 * Calculate on heap cache size./* w ww  . j  a  va  2 s  . c  om*/
 *
 * @param conf the conf
 * @return the long
 */
private long calculateOnHeapCacheSize(Configuration conf) {
    float cachePercentage = conf.getFloat(HEAP_BLOCK_CACHE_MEMORY_RATIO, DEFAULT_HEAP_BLOCK_CACHE_MEMORY_RATIO);
    if (cachePercentage == 0L) {
        // block cache disabled on heap
        return 0L;
    }
    if (cachePercentage > 1.0) {
        throw new IllegalArgumentException(
                HEAP_BLOCK_CACHE_MEMORY_RATIO + " must be between 0.0 and 1.0, and not > 1.0");
    }

    // Calculate the amount of heap to give the heap.
    MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    long cacheSize = (long) (mu.getMax() * cachePercentage);
    return cacheSize;
}

From source file:org.leo.benchmark.Benchmark.java

/**
 * @param collectionClass//from  ww  w.  j a v a 2 s .  c o  m
 * @throws NoSuchMethodException
 * @throws SecurityException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void runMemoryBench(List<Class<? extends Collection>> collectionClasses) {
    for (Class<? extends Collection> clazz : collectionClasses) {
        try {
            // run some gc
            heavyGc();
            long usedMemory = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
            Constructor<? extends Collection> constructor = clazz.getDeclaredConstructor((Class<?>[]) null);
            constructor.setAccessible(true);
            // do the test on 100 objects, to be more accurate
            for (int i = 0; i < 100; i++) {
                this.collection = (Collection<String>) constructor.newInstance();
                // polulate
                collection.addAll(defaultCtx);
                warmUp();
            }
            // measure size
            long objectSize = (long) ((ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed()
                    - usedMemory) / 100f);
            System.out.println(clazz.getCanonicalName() + " Object size : " + objectSize + " bytes");
            memoryResults.put((Class<? extends Collection<?>>) clazz, objectSize);
            collection.clear();
            collection = null;
        } catch (Exception e) {
            System.err.println("Failed running benchmark on class " + clazz.getCanonicalName());
            e.printStackTrace();
        }
    }
}

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

/** Show the information of graph data Memory used.*/
@Override/*  w ww  .j  a v a2s  .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.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(//  ww w . ja va 2  s.c om
            "<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.evolveum.midpoint.gui.api.util.WebComponentUtil.java

public static double getMaxRam() {
    int MB = 1024 * 1024;

    MemoryMXBean mBean = ManagementFactory.getMemoryMXBean();
    long maxHeap = mBean.getHeapMemoryUsage().getMax();
    long maxNonHeap = mBean.getNonHeapMemoryUsage().getMax();

    return (maxHeap + maxNonHeap) / MB;
}

From source file:com.evolveum.midpoint.gui.api.util.WebComponentUtil.java

public static double getRamUsage() {
    int MB = 1024 * 1024;

    MemoryMXBean mBean = ManagementFactory.getMemoryMXBean();
    long usedHead = mBean.getHeapMemoryUsage().getUsed();
    long usedNonHeap = mBean.getNonHeapMemoryUsage().getUsed();

    return (usedHead + usedNonHeap) / MB;
}