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:org.soitoolkit.commons.mule.util.MiscUtil.java

private static void printMemUsage() {
    int mb = 1024 * 1024;

    MemoryMXBean mxb = ManagementFactory.getMemoryMXBean();
    MemoryUsage hm = mxb.getHeapMemoryUsage();
    MemoryUsage nhm = mxb.getNonHeapMemoryUsage();
    //      int finalizable = mxb.getObjectPendingFinalizationCount();

    logger.trace("Heap Memory:  init/used/committed/max=" + hm.getInit() / mb + "/" + hm.getUsed() / mb + "/"
            + hm.getCommitted() / mb + "/" + hm.getMax() / mb);
    logger.trace("Non-Heap Mem: init/used/committed/max=" + nhm.getInit() / mb + "/" + nhm.getUsed() / mb + "/"
            + nhm.getCommitted() / mb + "/" + nhm.getMax() / mb);
    //                 logger.trace("finalizable: " + finalizable);

    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    logger.trace("Used/Free/Total/Max:"
            //Print used memory
            + (runtime.totalMemory() - runtime.freeMemory()) / mb + "/"

            //Print free memory
            + runtime.freeMemory() / mb + "/"

            //Print total available memory
            + runtime.totalMemory() / mb + "/"

            //Print Maximum available memory
            + runtime.maxMemory() / mb);
}

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;/*  w ww  .  j  av  a2  s  . c  o 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:de.unisb.cs.st.javalanche.mutation.runtime.jmx.MutationMxClient.java

public static boolean connect(int i) {
    JMXConnector jmxc = null;/*from w  w  w  . j av a2  s.com*/
    JMXServiceURL url = null;

    try {
        url = new JMXServiceURL(MXBeanRegisterer.ADDRESS + i);
        jmxc = JMXConnectorFactory.connect(url, null);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        return false;
        // System.out.println("Could not connect to address: " + url);
        // e.printStackTrace();
    }
    if (jmxc != null) {
        try {
            MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
            ObjectName objectName = new ObjectName(MXBeanRegisterer.OBJECT_NAME);
            Object numberOfMutations = mbsc.getAttribute(objectName, "NumberOfMutations");
            Object currentTest = mbsc.getAttribute(objectName, "CurrentTest");
            Object currentMutation = mbsc.getAttribute(objectName, "CurrentMutation");
            Object allMutations = mbsc.getAttribute(objectName, "Mutations");
            Object mutationsDuration = mbsc.getAttribute(objectName, "MutationDuration");
            Object testDuration = mbsc.getAttribute(objectName, "TestDuration");
            //            Object mutationSummary = mbsc.getAttribute(objectName,
            //                  "MutationSummary");

            final RuntimeMXBean remoteRuntime = ManagementFactory.newPlatformMXBeanProxy(mbsc,
                    ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);

            final MemoryMXBean remoteMemory = ManagementFactory.newPlatformMXBeanProxy(mbsc,
                    ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
            System.out.print("Connection: " + i + "  ");
            System.out.println("Target VM: " + remoteRuntime.getName() + " - " + remoteRuntime.getVmVendor()
                    + " - " + remoteRuntime.getSpecVersion() + " - " + remoteRuntime.getVmVersion());
            System.out.println(
                    "Running for: " + DurationFormatUtils.formatDurationHMS(remoteRuntime.getUptime()));
            System.out
                    .println("Memory usage: Heap - " + formatMemory(remoteMemory.getHeapMemoryUsage().getUsed())
                            + "  Non Heap - " + formatMemory(remoteMemory.getNonHeapMemoryUsage().getUsed()));

            String mutationDurationFormatted = DurationFormatUtils
                    .formatDurationHMS(Long.parseLong(mutationsDuration.toString()));
            String testDurationFormatted = DurationFormatUtils
                    .formatDurationHMS(Long.parseLong(testDuration.toString()));
            if (DEBUG_ADD) {
                System.out.println("Classpath: " + remoteRuntime.getClassPath());
                System.out.println("Args: " + remoteRuntime.getInputArguments());
                System.out.println("All Mutations: " + allMutations);
            }
            //            System.out.println(mutationSummary);
            System.out.println(
                    "Current mutation (Running for: " + mutationDurationFormatted + "): " + currentMutation);
            System.out.println("Mutations tested: " + numberOfMutations);
            System.out.println("Current test:   (Running for: " + testDurationFormatted + "): " + currentTest);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (AttributeNotFoundException e) {
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            e.printStackTrace();
        } catch (MBeanException e) {
            e.printStackTrace();
        } catch (ReflectionException e) {
            e.printStackTrace();
        } finally {
            try {
                jmxc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return true;
}

From source file:com.chinamobile.bcbsp.comm.io.util.MemoryAllocator.java

/** Refresh memory status with current JVM status. */
private void refreshMemoryStatus() {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
    used = memoryUsage.getUsed();/*from w w  w .j av  a 2s  .  c  om*/
    committed = memoryUsage.getCommitted();
    maxHeapSize = memoryUsage.getMax();
    remain = maxHeapSize - used;
}

From source file:com.chinamobile.bcbsp.comm.io.util.MemoryAllocator.java

/** Show the information of memory used. */
public void PrintMemoryInfo(Log LOG) {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
    long usedNow = memoryUsage.getUsed();
    long committedNow = memoryUsage.getCommitted();
    long maxHeapSizeNow = memoryUsage.getMax();
    long remainNow = maxHeapSize - used;
    LOG.info("Memory Usage **********************************************");
    LOG.info("Memory  Max ****************** " + maxHeapSizeNow);
    LOG.info("Memory Commit **************** " + committedNow + "-----Percents: "
            + committedNow * 1.0f / maxHeapSizeNow);
    LOG.info("Memory Used ****************** " + usedNow + "-----Percents: " + usedNow * 1.0f / maxHeapSizeNow);
    LOG.info("Memory Remain **************** " + remainNow + "-----Percents: "
            + remainNow * 1.0f / maxHeapSizeNow);
}

From source file:it.damore.tomee.envmonitor.services.EnvMonitorService.java

@GET
@Path("monitor")
@Produces({ MediaType.APPLICATION_JSON })
public EnvironmentConfig getEnvConfig() throws IllegalAccessException, InvocationTargetException {
    logger.info("received a request...");

    int mb = 1024 * 1024;
    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    EnvironmentConfig b = new EnvironmentConfig();
    b.setMaxMemory(runtime.maxMemory() / mb);
    b.setFreeMemory(runtime.freeMemory() / mb);
    b.setTotalMemory(runtime.totalMemory() / mb);
    b.setSystemProperties(System.getProperties());

    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    LocalRuntimeMXBean myRuntimeMXBean = new LocalRuntimeMXBean();
    BeanUtils.copyProperties(myRuntimeMXBean, runtimeMXBean);
    b.setRuntimeMXBean(myRuntimeMXBean);

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    LocalMemoryMXBean myMemoryMXBean = new LocalMemoryMXBean();
    myMemoryMXBean.setHeapMemoryUsage(memoryMXBean.getHeapMemoryUsage());
    myMemoryMXBean.setNonHeapMemoryUsage(memoryMXBean.getNonHeapMemoryUsage());
    myMemoryMXBean.setObjectPendingFinalizationCount(memoryMXBean.getObjectPendingFinalizationCount());
    b.setMemoryMXBean(myMemoryMXBean);/*from   w ww. j  a  v a2s  . c o  m*/

    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    LocalOperatingSystemMXBean myOperatingSystemMXBean = new LocalOperatingSystemMXBean();
    BeanUtils.copyProperties(myOperatingSystemMXBean, operatingSystemMXBean);
    b.setOperatingSystemMXBean(myOperatingSystemMXBean);

    return b;
}

From source file:it.geosolutions.geobatch.ui.mvc.MemoryController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ModelAndView mav = new ModelAndView("memory"); // jsp
    final MemoryMXBean mmxbean = ManagementFactory.getMemoryMXBean();
    mav.addObject("objectPendingFinalizationCount", mmxbean.getObjectPendingFinalizationCount());
    mav.addObject("nonHeapMemoryUsage", mmxbean.getNonHeapMemoryUsage());
    mav.addObject("heapMemoryUsage", mmxbean.getHeapMemoryUsage());
    mav.addObject("memoryPoolBeansList", ManagementFactory.getMemoryPoolMXBeans());

    return mav;/*from w w w.  ja  v  a2  s.  c  om*/
}

From source file:com.thoughtworks.go.server.service.support.ServerRuntimeInformationProvider.java

private void memoryInfo(MemoryMXBean memoryMXBean, InformationStringBuilder builder) {
    builder.addSection("Memory information");

    builder.append(String.format("Heap:\n%s\nNon-Heap:\n%s\nPending Finalization: %s\n",
            format(memoryMXBean.getHeapMemoryUsage()), format(memoryMXBean.getNonHeapMemoryUsage()),
            memoryMXBean.getObjectPendingFinalizationCount()));
}

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.alibaba.jstorm.utils.JStormUtils.java

public static Double getMemUsage() {
    if (OSInfo.isLinux() == true) {
        try {/*w  w w . j  av a2 s.c  om*/
            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());
}