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:rocks.inspectit.shared.all.util.UnderlyingSystemInfo.java

/**
 * Tests if the compressed pointers are used. Note that this method will return true only if the
 * JVM is 64bit, ignoring the fact that the 32bit JVM can also have
 * <code>+UseCompressedOops</code> argument. This method has been tested with Sun & IBM virtual
 * machine, and behavior with different providers is unknown.
 * <p>//ww  w  . java 2 s .  c o  m
 * IMPORTANT (SUN & ORACLE): Compressed oops is supported and enabled by default in Java SE 6u23
 * and later. In Java SE 7, use of compressed oops is the default for 64-bit JVM processes when
 * -Xmx isn't specified and for values of -Xmx less than 32 gigabytes. For JDK 6 before the 6u23
 * release, use the -XX:+UseCompressedOops flag with the java command to enable the feature.
 * <p>
 * IMPORTANT (IBM): From Java 6 SR 5, 64-bit JVMs recognize the following Oracle JVM options:
 * -XX:+UseCompressedOops This enables compressed references in 64-bit JVMs. It is identical to
 * specifying the -Xcompressedrefs option. -XX:-UseCompressedOops This prevents use of
 * compressed references in 64-bit JVMs.
 *
 * @return True only if JVM is 64bit and compressed oops are used.
 */
private static boolean isCompressedOops() {
    if (IS_64BIT) {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        if (null != runtimeMXBean) {
            List<String> arguments = runtimeMXBean.getInputArguments();
            for (String argument : arguments) {
                if ((argument.indexOf("+UseCompressedOops") != -1)
                        || (argument.indexOf("compressedrefs") != -1)) {
                    return true;
                } else if (argument.indexOf("-UseCompressedOops") != -1) {
                    return false;
                }
            }
        }

        switch (getJvmProvider()) {
        case SUN:
        case ORACLE:
            if (getJavaVersion() == JavaVersion.JAVA_1_7) {
                long max = Runtime.getRuntime().maxMemory();
                return (max == Long.MAX_VALUE) || (max < MAX_COMPRESSED_OOPS_JAVA7_MEMORY);
            } else if (getJavaVersion() == JavaVersion.JAVA_1_6) {
                try {
                    int subversionIndexStart = JAVA_VERSION_TRIMMED.indexOf('_');
                    boolean isAbove6u23 = Integer
                            .parseInt(JAVA_VERSION_TRIMMED.substring(subversionIndexStart + 1)) >= 23;
                    return isAbove6u23;
                } catch (NumberFormatException e) {
                    break;
                }
            }
            break;

        default:
            break;
        }
    }
    return false;
}

From source file:info.novatec.inspectit.util.UnderlyingSystemInfo.java

/**
 * Tests if the compressed pointers are used. Note that this method will return true only if the
 * JVM is 64bit, ignoring the fact that the 32bit JVM can also have
 * <code>+UseCompressedOops</code> argument. This method has been tested with Sun & IBM virtual
 * machine, and behavior with different providers is unknown.
 * <p>//  ww  w.ja v  a  2s.c o  m
 * IMPORTANT (SUN & ORACLE): Compressed oops is supported and enabled by default in Java SE 6u23
 * and later. In Java SE 7, use of compressed oops is the default for 64-bit JVM processes when
 * -Xmx isn't specified and for values of -Xmx less than 32 gigabytes. For JDK 6 before the 6u23
 * release, use the -XX:+UseCompressedOops flag with the java command to enable the feature.
 * <p>
 * IMPORTANT (IBM): From Java 6 SR 5, 64-bit JVMs recognize the following Oracle JVM options:
 * -XX:+UseCompressedOops This enables compressed references in 64-bit JVMs. It is identical to
 * specifying the -Xcompressedrefs option. -XX:-UseCompressedOops This prevents use of
 * compressed references in 64-bit JVMs.
 * 
 * @return True only if JVM is 64bit and compressed oops are used.
 */
private static boolean isCompressedOops() {
    if (IS_64BIT) {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        if (null != runtimeMXBean) {
            List<String> arguments = runtimeMXBean.getInputArguments();
            for (String argument : arguments) {
                if (argument.indexOf("+UseCompressedOops") != -1 || argument.indexOf("compressedrefs") != -1) {
                    return true;
                } else if (argument.indexOf("-UseCompressedOops") != -1) {
                    return false;
                }
            }
        }

        switch (getJvmProvider()) {
        case SUN:
        case ORACLE:
            if (getJavaVersion() == JavaVersion.JAVA_1_7) {
                long max = Runtime.getRuntime().maxMemory();
                return max == Long.MAX_VALUE || max < MAX_COMPRESSED_OOPS_JAVA7_MEMORY;
            } else if (getJavaVersion() == JavaVersion.JAVA_1_6) {
                try {
                    int subversionIndexStart = JAVA_VERSION_TRIMMED.indexOf('_');
                    boolean isAbove6u23 = Integer
                            .parseInt(JAVA_VERSION_TRIMMED.substring(subversionIndexStart + 1)) >= 23;
                    return isAbove6u23;
                } catch (NumberFormatException e) {
                    break;
                }
            }
            break;

        default:
            break;
        }
    }
    return false;
}

From source file:com.twosigma.beaker.core.Main.java

private static void writePID(BeakerConfig bkConfig) throws FileNotFoundException {

    String name = ManagementFactory.getRuntimeMXBean().getName();
    int at = name.indexOf("@");
    if (at > 0) {
        String pid = name.substring(0, at);
        String dir = bkConfig.getNginxServDirectory();
        PrintWriter out = new PrintWriter(dir + "/pid");
        out.println(pid);/*from  w  ww .j ava 2 s. co  m*/
        out.close();
    } else {
        logger.warn("warning, could not determine PID");
    }
}

From source file:gridool.util.system.SystemUtils.java

/** 
 * @return uptime in msec/*ww w  .jav  a  2s  . c o m*/
 */
public static long getUptime() {
    final RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
    return mx.getUptime();
}

From source file:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset.//from   w  w w.j  ava  2s .  co m
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}

From source file:com.searchbox.framework.web.SystemController.java

@ModelAttribute("jvmInfo")
public static Map<String, Object> getJvmInfo() {
    Map<String, Object> jvm = new HashMap<String, Object>();

    final String javaVersion = System.getProperty("java.specification.version", "unknown");
    final String javaVendor = System.getProperty("java.specification.vendor", "unknown");
    final String javaName = System.getProperty("java.specification.name", "unknown");
    final String jreVersion = System.getProperty("java.version", "unknown");
    final String jreVendor = System.getProperty("java.vendor", "unknown");
    final String vmVersion = System.getProperty("java.vm.version", "unknown");
    final String vmVendor = System.getProperty("java.vm.vendor", "unknown");
    final String vmName = System.getProperty("java.vm.name", "unknown");

    // Summary Info
    jvm.put("version", jreVersion + " " + vmVersion);
    jvm.put("name", jreVendor + " " + vmName);

    // details//from w  w w . j  a v  a2 s  .  c o  m
    Map<String, Object> java = new HashMap<String, Object>();
    java.put("vendor", javaVendor);
    java.put("name", javaName);
    java.put("version", javaVersion);
    jvm.put("spec", java);
    Map<String, Object> jre = new HashMap<String, Object>();
    jre.put("vendor", jreVendor);
    jre.put("version", jreVersion);
    jvm.put("jre", jre);
    Map<String, Object> vm = new HashMap<String, Object>();
    vm.put("vendor", vmVendor);
    vm.put("name", vmName);
    vm.put("version", vmVersion);
    jvm.put("vm", vm);

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

    // not thread safe, but could be thread local
    DecimalFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance(Locale.ROOT));

    Map<String, Object> mem = new HashMap<String, Object>();
    Map<String, Object> raw = new HashMap<String, Object>();
    long free = runtime.freeMemory();
    long max = runtime.maxMemory();
    long total = runtime.totalMemory();
    long used = total - free;
    double percentUsed = ((double) (used) / (double) max) * 100;
    raw.put("free", free);
    mem.put("free", humanReadableUnits(free, df));
    raw.put("total", total);
    mem.put("total", humanReadableUnits(total, df));
    raw.put("max", max);
    mem.put("max", humanReadableUnits(max, df));
    raw.put("used", used);
    mem.put("used", humanReadableUnits(used, df) + " (%" + df.format(percentUsed) + ")");
    raw.put("used%", percentUsed);

    mem.put("raw", raw);
    jvm.put("memory", mem);

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

        // the input arguments passed to the Java virtual machine
        // which does not include the arguments to the main method.
        jmx.put("commandLineArgs", mx.getInputArguments());

        jmx.put("startTime", new Date(mx.getStartTime()));
        jmx.put("upTimeMS", mx.getUptime());

    } catch (Exception e) {
        LOGGER.warn("Error getting JMX properties", e);
    }
    jvm.put("jmx", jmx);
    return jvm;
}

From source file:com.flexive.war.beans.admin.main.SystemInfoBean.java

/**
 * @return  the uptime as a formatted string.
 * @since 3.1//from  ww  w  . j a va  2  s .  com
 */
public String getUptime() {
    return DurationFormatUtils.formatDurationWords(ManagementFactory.getRuntimeMXBean().getUptime(), true,
            true);
}

From source file:org.midonet.midolman.Midolman.java

private void initialize(String[] args) throws IOException {
    // log git commit info
    Properties properties = new Properties();
    properties.load(getClass().getClassLoader().getResourceAsStream("git.properties"));
    log.info("MidoNet Agent main start... ---------");
    log.info("branch: {}", properties.get("git.branch"));
    log.info("commit.time: {}", properties.get("git.commit.time"));
    log.info("commit.id: {}", properties.get("git.commit.id"));
    log.info("commit.user: {}", properties.get("git.commit.user.name"));
    log.info("build.time: {}", properties.get("git.build.time"));
    log.info("build.user: {}", properties.get("git.build.user.name"));
    log.info("-------------------------------------");

    // log cmdline and JVM info
    log.info("Command-line arguments: {}", Arrays.toString(args));
    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    List<String> arguments = runtimeMxBean.getInputArguments();
    log.info("JVM options: ");
    for (String a : arguments) {
        log.info("  {}", a);
    }/*  w w w . ja  v a2s  . com*/
    log.info("-------------------------------------");

    log.info("Adding shutdown hook");
    Runtime.getRuntime().addShutdownHook(new Thread("shutdown") {
        @Override
        public void run() {
            doServicesCleanup();
        }
    });
}

From source file:eagle.executor.AlertExecutor.java

public void initMetricReportor() {
    String eagleServiceHost = config.getString(EagleConfigConstants.EAGLE_PROPS + "."
            + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.HOST);
    int eagleServicePort = config.getInt(EagleConfigConstants.EAGLE_PROPS + "."
            + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PORT);

    String username = config.hasPath(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE
            + "." + EagleConfigConstants.USERNAME)
                    ? config.getString(EagleConfigConstants.EAGLE_PROPS + "."
                            + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.USERNAME)
                    : null;//from  w  ww  . j  av a  2  s.co  m
    String password = config.hasPath(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE
            + "." + EagleConfigConstants.PASSWORD)
                    ? config.getString(EagleConfigConstants.EAGLE_PROPS + "."
                            + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PASSWORD)
                    : null;
    this.metricReport = new EagleSerivceMetricReport(eagleServiceHost, eagleServicePort, username, password);

    metricMap = new ConcurrentHashMap<String, Metric>();
    baseDimensions = new HashMap<String, String>();
    baseDimensions.put(AlertConstants.ALERT_EXECUTOR_ID, alertExecutorId);
    baseDimensions.put(AlertConstants.PARTITIONSEQ, String.valueOf(partitionSeq));
    baseDimensions.put(AlertConstants.SOURCE, ManagementFactory.getRuntimeMXBean().getName());
    baseDimensions.put(EagleConfigConstants.DATA_SOURCE,
            config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.DATA_SOURCE));
    baseDimensions.put(EagleConfigConstants.SITE,
            config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.SITE));

    dimensionsMap = new HashMap<String, Map<String, String>>();
    this.metricReportThread = new Thread() {
        @Override
        public void run() {
            runMetricReporter();
        }
    };
    this.metricReportThread.setDaemon(true);
    metricReportThread.start();
}

From source file:org.springframework.boot.context.initializer.LoggingApplicationContextInitializer.java

private String getPid() {
    String name = ManagementFactory.getRuntimeMXBean().getName();
    if (name != null) {
        return name.split("@")[0];
    }// w  ww . jav a  2s. c  o m
    return "????";
}