Example usage for java.lang.management ManagementFactory getRuntimeMXBean

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

Introduction

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

Prototype

public static RuntimeMXBean getRuntimeMXBean() 

Source Link

Document

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

Usage

From source file:org.paxle.core.monitorable.provider.impl.JmxMonitoring.java

public JmxMonitoring() {
    this.operatingSystem = ManagementFactory.getOperatingSystemMXBean();
    this.runtime = ManagementFactory.getRuntimeMXBean();

    // testing which operations are available
    this.testMethod(VAR_NAME_SYS_LOAD, this.operatingSystem, "systemLoadAverage");
    this.testMethod(VAR_NAME_OPEN_FILE_DESCR_COUNT, this.operatingSystem, "openFileDescriptorCount");
    this.testMethod(VAR_NAME_MAX_FILE_DESCR_COUNT, this.operatingSystem, "maxFileDescriptorCount");
    this.testMethod(VAR_NAME_VIRTUAL_MEMORY, this.operatingSystem, "committedVirtualMemorySize");
    this.testMethod(VAR_NAME_PHYSICAL_MEMORY, this.operatingSystem, "totalPhysicalMemorySize");
    this.testMethod(VAR_NAME_SWAP_SPACE, this.operatingSystem, "totalSwapSpaceSize");
    this.testMethod(VAR_NAME_CPU_TIME, this.operatingSystem, "processCpuTime");
    this.testMethod(VAR_NAME_UPTIME, this.runtime, "uptime");
    this.testMethod(VAR_NAME_STARTTIME, this.runtime, "startTime");
}

From source file:com.ery.estorm.zk.RecoverableZooKeeper.java

public RecoverableZooKeeper(String quorumServers, int sessionTimeout, Watcher watcher, int maxRetries,
        int retryIntervalMillis, String identifier) throws IOException {
    // TODO: Add support for zk 'chroot'; we don't add it to the
    // quorumServers String as we should.
    this.zk = new ZooKeeper(quorumServers, sessionTimeout, watcher);
    this.retryCounterFactory = new RetryCounterFactory(maxRetries, retryIntervalMillis);

    if (identifier == null || identifier.length() == 0) {
        // the identifier = processID@hostName
        identifier = ManagementFactory.getRuntimeMXBean().getName();
    }/*from  w  w  w  .ja  v a 2s  . co  m*/
    LOG.info("Process identifier=" + identifier + " connecting to ZooKeeper ensemble=" + quorumServers);
    this.identifier = identifier;
    this.id = Bytes.toBytes(identifier);

    this.watcher = watcher;
    this.sessionTimeout = sessionTimeout;
    this.quorumServers = quorumServers;
    salter = new SecureRandom();
}

From source file:com.ery.ertc.estorm.util.JVM.java

/**
 * Get the number of opened filed descriptor for the runtime jvm. If Oracle java, it will use the com.sun.management interfaces.
 * Otherwise, this methods implements it (linux only).
 * /*from  w  ww  . ja v  a  2  s. c om*/
 * @return number of open file descriptors for the jvm
 */
public long getOpenFileDescriptorCount() {

    Long ofdc;

    if (!ibmvendor) {
        ofdc = runUnixMXBeanMethod("getOpenFileDescriptorCount");
        return (ofdc != null ? ofdc.longValue() : -1);
    }
    InputStream in = null;
    BufferedReader output = null;
    try {
        // need to get the PID number of the process first
        RuntimeMXBean rtmbean = ManagementFactory.getRuntimeMXBean();
        String rtname = rtmbean.getName();
        String[] pidhost = rtname.split("@");

        // using linux bash commands to retrieve info
        Process p = Runtime.getRuntime()
                .exec(new String[] { "bash", "-c", "ls /proc/" + pidhost[0] + "/fdinfo | wc -l" });
        in = p.getInputStream();
        output = new BufferedReader(new InputStreamReader(in));
        String openFileDesCount;
        if ((openFileDesCount = output.readLine()) != null)
            return Long.parseLong(openFileDesCount);
    } catch (IOException ie) {
        LOG.warn("Not able to get the number of open file descriptors", ie);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                LOG.warn("Not able to close the InputStream", e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOG.warn("Not able to close the InputStream", e);
            }
        }
    }
    return -1;
}

From source file:org.apache.hadoop.hbase.util.JVM.java

/**
 * Get the number of opened filed descriptor for the runtime jvm.
 * If Oracle java, it will use the com.sun.management interfaces.
 * Otherwise, this methods implements it (linux only).  
 * @return number of open file descriptors for the jvm
 *///from  w  ww .ja  v  a2  s  .c  o m
public long getOpenFileDescriptorCount() {

    Long ofdc;

    if (!ibmvendor) {
        ofdc = runUnixMXBeanMethod("getOpenFileDescriptorCount");
        return (ofdc != null ? ofdc.longValue() : -1);
    }
    InputStream in = null;
    BufferedReader output = null;
    try {
        //need to get the PID number of the process first
        RuntimeMXBean rtmbean = ManagementFactory.getRuntimeMXBean();
        String rtname = rtmbean.getName();
        String[] pidhost = rtname.split("@");

        //using linux bash commands to retrieve info
        Process p = Runtime.getRuntime()
                .exec(new String[] { "bash", "-c", "ls /proc/" + pidhost[0] + "/fdinfo | wc -l" });
        in = p.getInputStream();
        output = new BufferedReader(new InputStreamReader(in));
        String openFileDesCount;
        if ((openFileDesCount = output.readLine()) != null)
            return Long.parseLong(openFileDesCount);
    } catch (IOException ie) {
        LOG.warn("Not able to get the number of open file descriptors", ie);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                LOG.warn("Not able to close the InputStream", e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOG.warn("Not able to close the InputStream", e);
            }
        }
    }
    return -1;
}

From source file:com.sm.transport.Utils.java

/**
 *
 * @return Process ID/* w ww . ja  va2 s  .  c  om*/
 */
public static int getPID() {
    String str = ManagementFactory.getRuntimeMXBean().getName();
    String pid = str.substring(0, str.indexOf("@"));
    return Integer.valueOf(pid);
}

From source file:com.opengamma.web.WebAbout.java

/**
 * Gets the uptime.
 * @return the JVM uptime
 */
public Duration getJvmUptime() {
    return Duration.ofMillis(ManagementFactory.getRuntimeMXBean().getUptime());
}

From source file:co.aikar.timings.TimingsExport.java

/**
 * Checks if any pending reports are being requested, and builds one if needed.
 *//*from  ww w .  j  av  a  2s . c  o m*/
static void reportTimings() {
    if (requestingReport.isEmpty()) {
        return;
    }
    TimingsReportListener listeners = new TimingsReportListener(requestingReport);
    listeners.addConsoleIfNeeded();

    requestingReport.clear();
    long now = System.currentTimeMillis();
    final long lastReportDiff = now - lastReport;
    if (lastReportDiff < 60000) {
        listeners.sendMessage(ChatColor.RED + "Please wait at least 1 minute in between Timings reports. ("
                + (int) ((60000 - lastReportDiff) / 1000) + " seconds)");
        listeners.done();
        return;
    }
    final long lastStartDiff = now - TimingsManager.timingStart;
    if (lastStartDiff < 180000) {
        listeners.sendMessage(ChatColor.RED
                + "Please wait at least 3 minutes before generating a Timings report. Unlike Timings v1, v2 benefits from longer timings and is not as useful with short timings. ("
                + (int) ((180000 - lastStartDiff) / 1000) + " seconds)");
        listeners.done();
        return;
    }
    listeners.sendMessage(ChatColor.GREEN + "Preparing Timings Report...");
    lastReport = now;
    Map parent = createObject(
            // Get some basic system details about the server
            pair("version", Bukkit.getVersion()), pair("maxplayers", Bukkit.getMaxPlayers()),
            pair("start", TimingsManager.timingStart / 1000), pair("end", System.currentTimeMillis() / 1000),
            pair("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000));
    if (!TimingsManager.privacy) {
        appendObjectData(parent, pair("server", Bukkit.getServerName()),
                pair("motd", Bukkit.getServer().getMotd()),
                pair("online-mode", Bukkit.getServer().getOnlineMode()),
                pair("icon", Bukkit.getServer().getServerIcon().getData()));
    }

    final Runtime runtime = Runtime.getRuntime();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();

    parent.put("system", createObject(pair("timingcost", getCost()),
            pair("name", System.getProperty("os.name")), pair("version", System.getProperty("os.version")),
            pair("jvmversion", System.getProperty("java.version")), pair("arch", System.getProperty("os.arch")),
            pair("maxmem", runtime.maxMemory()), pair("cpu", runtime.availableProcessors()),
            pair("runtime", ManagementFactory.getRuntimeMXBean().getUptime()),
            pair("flags", StringUtils.join(runtimeBean.getInputArguments(), " ")),
            pair("gc",
                    toObjectMapper(ManagementFactory.getGarbageCollectorMXBeans(),
                            input -> pair(input.getName(),
                                    toArray(input.getCollectionCount(), input.getCollectionTime()))))));

    Set<Material> tileEntityTypeSet = Sets.newHashSet();
    Set<EntityType> entityTypeSet = Sets.newHashSet();

    int size = HISTORY.size();
    TimingHistory[] history = new TimingHistory[size + 1];
    int i = 0;
    for (TimingHistory timingHistory : HISTORY) {
        tileEntityTypeSet.addAll(timingHistory.tileEntityTypeSet);
        entityTypeSet.addAll(timingHistory.entityTypeSet);
        history[i++] = timingHistory;
    }

    history[i] = new TimingHistory(); // Current snapshot
    tileEntityTypeSet.addAll(history[i].tileEntityTypeSet);
    entityTypeSet.addAll(history[i].entityTypeSet);

    Map handlers = createObject();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
        for (TimingHandler id : group.handlers) {
            if (!id.isTimed() && !id.isSpecial()) {
                continue;
            }
            handlers.put(id.id, toArray(group.id, id.name));
        }
    }

    parent.put("idmap",
            createObject(
                    pair("groups",
                            toObjectMapper(
                                    TimingIdentifier.GROUP_MAP.values(), group -> pair(group.id, group.name))),
                    pair("handlers", handlers), pair(
                            "worlds",
                            toObjectMapper(TimingHistory.worldMap.entrySet(),
                                    input -> pair(input.getValue(), input.getKey()))),
                    pair("tileentity",
                            toObjectMapper(tileEntityTypeSet, input -> pair(input.getId(), input.name()))),
                    pair("entity",
                            toObjectMapper(entityTypeSet, input -> pair(input.getTypeId(), input.name())))));

    // Information about loaded plugins

    parent.put("plugins",
            toObjectMapper(Bukkit.getPluginManager().getPlugins(), plugin -> pair(plugin.getName(),
                    createObject(pair("version", plugin.getDescription().getVersion()),
                            pair("description",
                                    String.valueOf(plugin.getDescription().getDescription()).trim()),
                            pair("website", plugin.getDescription().getWebsite()),
                            pair("authors", StringUtils.join(plugin.getDescription().getAuthors(), ", "))))));

    // Information on the users Config

    parent.put("config", createObject(pair("bukkit", mapAsJSON(Bukkit.spigot().getConfig(), null))));

    new TimingsExport(listeners, parent, history).start();
}

From source file:lineage2.gameserver.network.telnet.commands.TelnetStatus.java

/**
 * Method getUptime.//from ww  w .j a va2 s .c om
 * @return String
 */
public static String getUptime() {
    return DurationFormatUtils.formatDurationHMS(ManagementFactory.getRuntimeMXBean().getUptime());
}

From source file:eu.openanalytics.rsb.component.SystemHealthResource.java

@GET
@Path("/info")
@Produces({ Constants.RSB_XML_CONTENT_TYPE, Constants.RSB_JSON_CONTENT_TYPE })
public NodeInformation getInfo(@Context final ServletContext sc) {
    final NodeInformation info = Util.REST_OBJECT_FACTORY.createNodeInformation();

    info.setName(getConfiguration().getNodeName());
    info.setHealthy(nodeHealthy.get());/* www  .j  a  va2  s .c  o  m*/
    info.setRsbVersion(getClass().getPackage().getImplementationVersion());
    info.setServletContainerInfo(sc.getServerInfo());

    final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    info.setOsLoadAverage(operatingSystemMXBean.getSystemLoadAverage());

    final Runtime runtime = Runtime.getRuntime();
    info.setJvmMaxMemory(runtime.maxMemory());
    info.setJvmFreeMemory(runtime.freeMemory());

    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    final long uptimeMilliseconds = runtimeMXBean.getUptime();
    info.setUptime(uptimeMilliseconds);
    info.setUptimeText(DurationFormatUtils.formatDurationWords(uptimeMilliseconds, true, true));

    return info;
}

From source file:util.PiazzaLogger.java

/**
 * Generates a LoggerPayload with default values populated
 * //from  w w  w  .  j  ava  2  s  . c  om
 * @return LoggerPayload payload object
 */
private LoggerPayload getLoggerPayload() {
    LoggerPayload loggerPayload = new LoggerPayload();
    loggerPayload.setApplication(serviceName);
    loggerPayload.setProcess(ManagementFactory.getRuntimeMXBean().getName());
    try {
        loggerPayload.setHostName(InetAddress.getLocalHost().getHostName());
    } catch (Exception exception) {
        LOGGER.error("Could not get hostname for component.", exception);
    }
    return loggerPayload;
}