Example usage for java.lang.management RuntimeMXBean getUptime

List of usage examples for java.lang.management RuntimeMXBean getUptime

Introduction

In this page you can find the example usage for java.lang.management RuntimeMXBean getUptime.

Prototype

public long getUptime();

Source Link

Document

Returns the uptime of the Java virtual machine in milliseconds.

Usage

From source file:org.apache.solr.handler.admin.SystemInfoHandler.java

/**
 * Get JVM Info - including memory info/*  w  w  w.ja va 2  s  . c  om*/
 */
public static SimpleOrderedMap<Object> getJvmInfo() {
    SimpleOrderedMap<Object> jvm = new SimpleOrderedMap<Object>();
    jvm.add("version", System.getProperty("java.vm.version"));
    jvm.add("name", System.getProperty("java.vm.name"));

    Runtime runtime = Runtime.getRuntime();
    jvm.add("processors", runtime.availableProcessors());

    long used = runtime.totalMemory() - runtime.freeMemory();
    // not thread safe, but could be thread local
    DecimalFormat df = new DecimalFormat("#.#");
    double percentUsed = ((double) (used) / (double) runtime.maxMemory()) * 100;

    SimpleOrderedMap<Object> mem = new SimpleOrderedMap<Object>();
    mem.add("free", humanReadableUnits(runtime.freeMemory(), df));
    mem.add("total", humanReadableUnits(runtime.totalMemory(), df));
    mem.add("max", humanReadableUnits(runtime.maxMemory(), df));
    mem.add("used", humanReadableUnits(used, df) + " (%" + df.format(percentUsed) + ")");
    jvm.add("memory", mem);

    // JMX properties -- probably should be moved to a different handler
    SimpleOrderedMap<Object> jmx = new SimpleOrderedMap<Object>();
    try {
        RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
        jmx.add("bootclasspath", mx.getBootClassPath());
        jmx.add("classpath", mx.getClassPath());

        // the input arguments passed to the Java virtual machine
        // which does not include the arguments to the main method.
        jmx.add("commandLineArgs", mx.getInputArguments());
        // a map of names and values of all system properties.
        //jmx.add( "SYSTEM PROPERTIES", mx.getSystemProperties());

        jmx.add("startTime", new Date(mx.getStartTime()));
        jmx.add("upTimeMS", mx.getUptime());
    } catch (Exception e) {
        log.warn("Error getting JMX properties", e);
    }
    jvm.add("jmx", jmx);
    return jvm;
}

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

@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }/*from  w  w  w  .  ja  v  a2s .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.fluentd.jvmwatcher.data.JvmStateLog.java

/**
 * @param clientPrixy/*from   ww w  . j  a  va 2  s . c o m*/
 * @return
 */
public static JvmStateLog makeJvmStateLog(JvmClientProxy clientProxy) {
    JvmStateLog ret = new JvmStateLog();

    try {
        // set log time
        ret.logDateTime_ = System.currentTimeMillis();

        // ClassLoadingMXBean
        ClassLoadingMXBean classLoadingBean = clientProxy.getClassLoadingMXBean();
        if (null != classLoadingBean) {
            ret.classLoadedCount_ = classLoadingBean.getLoadedClassCount();
            ret.classUnloadedCount_ = classLoadingBean.getUnloadedClassCount();
            ret.classTotalLoadedCount_ = classLoadingBean.getTotalLoadedClassCount();
        }

        // CompilationMXBean
        CompilationMXBean compilationBean = clientProxy.getCompilationMXBean();
        if (null != compilationBean) {
            ret.compileTime_ = compilationBean.getTotalCompilationTime();
        }

        // MemoryMXBean
        MemoryMXBean memoryBean = clientProxy.getMemoryMXBean();
        if (null != memoryBean) {
            ret.heapSize_ = memoryBean.getHeapMemoryUsage();
            ret.notheapSize_ = memoryBean.getNonHeapMemoryUsage();
            ret.pendingFinalizationCount_ = memoryBean.getObjectPendingFinalizationCount();
        }

        // ThreadMXBean
        ThreadMXBean threadBean = clientProxy.getThreadMXBean();
        if (null != threadBean) {
            ret.threadCount_ = threadBean.getThreadCount();
            ret.daemonThreadCount_ = threadBean.getDaemonThreadCount();
            ret.peakThreadCount_ = threadBean.getPeakThreadCount();
        }

        // OperatingSystemMXBean
        OperatingSystemMXBean OpeSysBean = clientProxy.getOperatingSystemMXBean();
        if (null != OpeSysBean) {
            ret.osAvailableProcessors_ = OpeSysBean.getAvailableProcessors();
            ret.osSystemLoadAverage_ = OpeSysBean.getSystemLoadAverage();
        }

        // com.sun.management.OperatingSystemMXBean
        com.sun.management.OperatingSystemMXBean sunOpeSysBean = clientProxy.getSunOperatingSystemMXBean();
        if (null != sunOpeSysBean) {
            ret.committedVirtualMemorySize_ = sunOpeSysBean.getCommittedVirtualMemorySize();
            ret.freePhysicalMemorySize_ = sunOpeSysBean.getFreePhysicalMemorySize();
            ret.freeSwapSpaceSize_ = sunOpeSysBean.getFreeSwapSpaceSize();
            ret.processCpuTime_ = sunOpeSysBean.getProcessCpuTime();
            ret.totalPhysicalMemorySize_ = sunOpeSysBean.getTotalPhysicalMemorySize();
            ret.totalSwapSpaceSize_ = sunOpeSysBean.getTotalSwapSpaceSize();
        }

        // RuntimeMXBean
        RuntimeMXBean runtimeBean = clientProxy.getRuntimeMXBean();
        if (null != runtimeBean) {
            ret.jvmUpTime_ = runtimeBean.getUptime();
        }

        // MemoryPoolMXBean
        Collection<MemoryPoolClientProxy> memoryPoolBeansColl = clientProxy.getMemoryPoolClientProxies();
        if (null != memoryPoolBeansColl) {
            ret.memoryPoolStateColl_ = new ArrayList<MemoryPoolState>();
            for (MemoryPoolClientProxy elem : memoryPoolBeansColl) {
                if (null != elem) {
                    MemoryPoolState state = elem.getStat();
                    if (null != state) {
                        // add MemoryPoolState
                        ret.memoryPoolStateColl_.add(state);
                    }
                }
            }
        }

        // GarbageCollectorMXBean
        Collection<GarbageCollectorMXBean> garbageCollBeansColl = clientProxy.getGarbageCollectorMXBeans();
        if (null != garbageCollBeansColl) {
            ret.gcCollectorState_ = new ArrayList<GarbageCollectorState>();
            for (GarbageCollectorMXBean elem : garbageCollBeansColl) {
                if (null != elem) {
                    long collectionCount = elem.getCollectionCount();
                    long collectionTime = elem.getCollectionTime();
                    String memoryManagerName = elem.getName();
                    GarbageCollectorState state = new GarbageCollectorState(memoryManagerName, collectionCount,
                            collectionTime);
                    // add GarbageCollectorState
                    ret.gcCollectorState_.add(state);
                }
            }
        }
    } catch (IOException ex) {
        log.error(ex);
        // close JvmClientProxy
        clientProxy.disconnect();
    } catch (Exception ex) {
        log.error(ex);
        // close JvmClientProxy
        clientProxy.disconnect();
    }

    return ret;
}

From source file:org.jwebsocket.plugins.system.SystemPlugIn.java

private void getJVMInfo(WebSocketConnector aConnector, Token aToken) {
    // check if user is allowed to run 'getjvminfo' command
    if (!hasAuthority(aConnector, NS_SYSTEM + ".getjvminfo")) {
        sendToken(aConnector, aConnector, createAccessDenied(aToken));
        return;/*ww  w  .  j a  v a2 s. c  om*/
    }

    Token lResponse = createResponse(aToken);
    RuntimeMXBean lBean = ManagementFactory.getRuntimeMXBean();
    MemoryMXBean lMemory = ManagementFactory.getMemoryMXBean();
    OperatingSystemMXBean lOS = ManagementFactory.getOperatingSystemMXBean();

    lResponse.setMap("data", new MapAppender().append("inputArguments", lBean.getInputArguments())
            .append("libraryPath", lBean.getLibraryPath())
            .append("managementSpecVersion", lBean.getManagementSpecVersion()).append("name", lBean.getName())
            .append("specName", lBean.getSpecName()).append("specVendor", lBean.getSpecVendor())
            .append("specVersion", lBean.getSpecVersion()).append("startTime", lBean.getStartTime())
            .append("systemProperties", lBean.getSystemProperties()).append("uptime", lBean.getUptime())
            .append("vmName", lBean.getVmName()).append("vmVendor", lBean.getVmVendor())
            .append("vmVersion", lBean.getVmVersion()).append("classPath", lBean.getClassPath())
            .append("osArch", lOS.getArch()).append("osAvailableProcessors", lOS.getAvailableProcessors())
            .append("osName", lOS.getName()).append("osVersion", lOS.getVersion())
            .append("osLoadAverage", lOS.getSystemLoadAverage())
            .append("heapMemoryUsed", lMemory.getHeapMemoryUsage().getUsed())
            .append("heapMemoryMax", lMemory.getHeapMemoryUsage().getMax())
            .append("heapMemoryInit", lMemory.getHeapMemoryUsage().getInit())
            .append("nonheapMemoryInit", lMemory.getNonHeapMemoryUsage().getInit())
            .append("nonheapMemoryMax", lMemory.getNonHeapMemoryUsage().getMax())
            .append("nonheapMemoryUsed", lMemory.getNonHeapMemoryUsage().getUsed()).getMap());

    sendToken(aConnector, lResponse);
}

From source file:org.nuxeo.ecm.admin.SystemInfoManager.java

public String getUptime() {
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
    long ut = bean.getUptime();
    long uts = ut / 1000;

    StringBuffer sb = new StringBuffer("Nuxeo Server UpTime : ");
    long nbDays = uts / (24 * 3600);
    if (nbDays > 0) {
        sb.append(nbDays + " days, ");
        uts = uts % (24 * 3600);/*from  w w w .  j  av a  2  s.  c o  m*/
    }
    long nbHours = uts / 3600;
    sb.append(nbHours + " h ");
    uts = uts % 3600;

    long nbMin = uts / 60;
    sb.append(nbMin + " m ");
    uts = uts % 60;

    sb.append(uts + " s  ");

    return sb.toString();
}

From source file:org.renjin.primitives.System.java

/**
 * Returns object of class "proc_time" which is a numeric vector of
 * length 5, containing the user, system, and total elapsed times for
 * the currently running R process, and the cumulative sum of user
 * and system times of any child processes spawned by it on which it
 * has waited. /*w  ww  .  j  av  a 2s.  c om*/
 *
 * _The user time is the CPU time charged for the execution of user
 *  instructions of the calling process. The system time is the CPU
 *  time charged for execution by the system on behalf of the calling
 *  process._
 */
@Builtin("proc.time")
public static DoubleVector procTime() {

    DoubleArrayVector.Builder result = new DoubleArrayVector.Builder();
    StringVector.Builder names = new StringVector.Builder();

    long totalCPUTime;
    long userCPUTime;
    long elapsedTime;

    // There doesn't seem to be any platform-independent way of accessing
    // CPU use for the whole JVM process, so we'll have to make do
    // with the timings for the thread we're running on.
    //
    // Additionally, the MX Beans may not be available in all environments,
    // so we need to fallback to app
    try {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        totalCPUTime = threadMXBean.getCurrentThreadCpuTime();
        userCPUTime = threadMXBean.getCurrentThreadUserTime();

        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        elapsedTime = runtimeMXBean.getUptime();
    } catch (Error e) {
        // ThreadMXBean is not available in all environments
        // Specifically, AppEngine will throw variously SecurityErrors or
        // ClassNotFoundErrors if we try to access these classes
        userCPUTime = totalCPUTime = java.lang.System.nanoTime();
        elapsedTime = new Date().getTime();
    }

    // user.self
    names.add("user.self");
    result.add(userCPUTime / NANOSECONDS_PER_SECOND);

    // sys.self
    names.add("sys.self");
    result.add((totalCPUTime - userCPUTime) / NANOSECONDS_PER_SECOND);

    // elapsed
    // (wall clock time)
    names.add("elapsed");
    result.add(elapsedTime / MILLISECONDS_PER_SECOND);

    // AFAIK, we don't have any platform independent way of accessing
    // this info.

    // user.child
    names.add("user.child");
    result.add(0);

    // sys.child
    names.add("sys.child");
    result.add(0);

    result.setAttribute(Symbols.NAMES, names.build());
    result.setAttribute(Symbols.CLASS, StringVector.valueOf("proc_time"));
    return result.build();

}

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;
}