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.liferayhub.pc.service.impl.PowerConsoleServiceImpl.java

public String runCommand(long userId, long companyId, String mode, String command) {
    String response = "";
    Date startDate = new Date();
    if ("server".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the Liferay Portal\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "uptime\t\t  Display the uptime of the portal\n" + "adduser\t\t Add a new user";
        } else if ("version".equalsIgnoreCase(command)) {
            response = ReleaseInfo.getReleaseInfo() + " running on "
                    + StringUtil.upperCaseFirstLetter(ServerDetector.getServerId());
        } else if ("date".equalsIgnoreCase(command)) {
            response = new Date().toString();
        } else if ("uptime".equalsIgnoreCase(command)) {
            response = getUptime(PortalUtil.getUptime().getTime());
        } else if (command.toLowerCase().startsWith("adduser")) {
            response = handleAddUser(userId, companyId, command);
        }/*from   w  w  w.  j  a  va2 s.co  m*/
    } else if ("db".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the database\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "<sql query>\t Display result of any SQL query";
        } else if ("date".equalsIgnoreCase(command)) {
            response = runSQLQuery("select now() \"\"");
        } else if ("version".equalsIgnoreCase(command)) {
            response = runSQLQuery(
                    "select '" + DBFactoryUtil.getDBFactory().getDB().getType() + "' as '', version() ''");
        } else
            response = runSQLQuery(command);
    } else if ("jvm".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\tShow this help message\n"
                    + "mem\t\t Display memory usage of the JVM\n"
                    + "osinfo\t  Display operating system info of the running JVM\n"
                    + "vminfo\t  Display VM info";
        } else if ("mem".equalsIgnoreCase(command)) {
            MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
            response = "Heap        : " + mem.getHeapMemoryUsage().toString();
            response += "\nNon Heap    : " + mem.getNonHeapMemoryUsage().toString();
            response += "\nFinalization: " + mem.getObjectPendingFinalizationCount() + " objects pending";
        } else if ("osinfo".equalsIgnoreCase(command)) {
            OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
            response = os.getName() + "[" + os.getArch() + "] " + os.getVersion() + " ("
                    + os.getAvailableProcessors() + " processors)";
            response += "\nLoad Average: " + os.getSystemLoadAverage();
        } else if ("vminfo".equalsIgnoreCase(command)) {
            RuntimeMXBean vm = ManagementFactory.getRuntimeMXBean();
            response = vm.getVmName() + " " + vm.getVmVersion() + " by " + vm.getVmVendor();
            response += "\n" + vm.getSpecName() + " " + vm.getSpecVersion() + " by " + vm.getSpecVendor();
            response += "\nStarted at: " + DateFormat.getInstance().format(new Date(vm.getStartTime()));
            response += "\nUptime    : " + getUptime(vm.getStartTime());
        } else {
            response = UNRECOGNIZED_COMMAND;
        }
    }
    // save command to database if it is not 'help'
    if (!command.startsWith("help")) {
        try {
            // add to history
            Date endDate = new Date();
            long id = CounterLocalServiceUtil.increment(CommandHistory.class.getName());
            CommandHistory history = CommandHistoryLocalServiceUtil.createCommandHistory(id);
            history.setCommand(command);
            history.setExecutionDate(startDate);
            history.setExecutionTime(endDate.getTime() - startDate.getTime());
            history.setMode(mode);
            history.setUserId(userId);
            CommandHistoryLocalServiceUtil.updateCommandHistory(history);
            // TODO: delete the oldest entry > MAX_HISTORY_SIZE
            // get the history size
            long historySize = 100;
            List<CommandHistory> historyList = CommandHistoryLocalServiceUtil
                    .findCommandHistoryByUserId(userId);
            if (historyList.size() >= historySize) {
                CommandHistoryLocalServiceUtil.deleteCommandHistory(historyList.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
    return response;
}

From source file:org.pepstock.jem.node.StartUpSystem.java

/**
 * If NODES_MAP contain at least a node with status different from STARTING
 * will return otherwise checks if the cluster have enough nodes to support
 * the persisted queue in memory. If the nodes are not enough the cluster
 * will wait for new joining nodes./*ww  w . java2s  .co m*/
 * 
 * @throws ConfigurationException
 */
private static void checkIfEnoughMembers() throws ConfigurationException {
    // by default the number of permits are 0
    ISemaphore semaphore = Main.getHazelcast().getSemaphore(SEMAPHORE);
    // check if exists a node of the cluster with status different from
    // STARTING if so return.
    List<Status> statusList = new ArrayList<Status>();
    statusList.add(Status.STARTING);
    List<NodeInfo> nodesInfo = NodeInfoUtility.getNodesInfoByStatus(statusList, true);
    if (!nodesInfo.isEmpty()) {
        return;
    }

    // times 2 because in memory there will be a replication copy
    long queueSize = calculateQueueSize() * 2;
    // calculate the number of nodes (exclude light member)
    Cluster cluster = Main.getHazelcast().getCluster();
    int membersNumber = cluster.getMembers().size();
    MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
    long freeMemoryForNode = bean.getHeapMemoryUsage().getMax() - bean.getHeapMemoryUsage().getUsed();
    // we consider each has at this point the same max and used memory
    // or we could insert this information in nodeInfo ?
    long clusterFreMemory = freeMemoryForNode * membersNumber;
    // we consider clusterFreMemory enough if is grather than the queueSize
    // + 20%
    long neededMemory = queueSize + (queueSize / 10) * 2;
    if (clusterFreMemory > neededMemory) {
        semaphore.release(membersNumber - 1);
        return;
    } else {
        LogAppl.getInstance().emit(NodeMessage.JEMC086W, clusterFreMemory / 1000, neededMemory / 1000);
        try {
            semaphore.acquire();
        } catch (Exception e) {
            throw new ConfigurationException(e);
        }
    }
}

From source file:org.rhq.enterprise.agent.promptcmd.GCPromptCommand.java

private void printGlobalMemoryUsage(PrintWriter out, final MemoryMXBean memoryMxBean) {
    printMemoryUsage(out, "GLOBAL", MemoryType.HEAP, memoryMxBean.getHeapMemoryUsage());
    printMemoryUsage(out, "GLOBAL", MemoryType.NON_HEAP, memoryMxBean.getNonHeapMemoryUsage());
}

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:ro.nextreports.server.web.debug.InfoUtil.java

public static List<Info> getGeneralJVMInfo() {
    List<Info> infos = new ArrayList<Info>();

    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    infos.add(new Info("uptime", "" + Duration.milliseconds(runtimeBean.getUptime()).toString()));
    infos.add(new Info("name", runtimeBean.getName()));
    infos.add(new Info("pid", runtimeBean.getName().split("@")[0]));

    OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean();
    infos.add(new Info("os name", "" + systemBean.getName()));
    infos.add(new Info("os version", "" + systemBean.getVersion()));
    infos.add(new Info("system load average", "" + systemBean.getSystemLoadAverage()));
    infos.add(new Info("available processors", "" + systemBean.getAvailableProcessors()));

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    infos.add(new Info("thread count", "" + threadBean.getThreadCount()));
    infos.add(new Info("peak thread count", "" + threadBean.getPeakThreadCount()));

    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    infos.add(new Info("heap memory used",
            FileUtils.byteCountToDisplaySize(memoryBean.getHeapMemoryUsage().getUsed())));
    infos.add(new Info("non-heap memory used",
            FileUtils.byteCountToDisplaySize(memoryBean.getNonHeapMemoryUsage().getUsed())));

    return infos;
}

From source file:test.integ.be.fedict.hsm.MonitoringTest.java

@Test
public void testJMXConnection() throws Exception {
    JMXServiceURL jmxServiceURL = new JMXServiceURL("service:jmx:remoting-jmx://localhost:9999");
    JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL);
    MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
    MemoryMXBean memoryMXBean = ManagementFactory.newPlatformMXBeanProxy(connection,
            ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
    MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
    LOG.debug("used heap memory: " + heapMemoryUsage.getUsed());
}