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:eu.over9000.skadi.Main.java

private static void printStartupInfo(final String[] args) {
    LOGGER.info("################################################################################");
    LOGGER.info("TIME:    " + LocalDateTime.now().toString());
    LOGGER.info("OS:      " + SystemUtils.OS_NAME + " " + SystemUtils.OS_VERSION + " " + SystemUtils.OS_ARCH);
    LOGGER.info("JAVA:    " + SystemUtils.JAVA_VERSION);
    LOGGER.info(//from w w  w  .j  av  a 2  s. co m
            "         " + SystemUtils.JAVA_RUNTIME_NAME + " <build " + SystemUtils.JAVA_RUNTIME_VERSION + ">");
    LOGGER.info("VM:      " + SystemUtils.JAVA_VM_NAME + " <build" + SystemUtils.JAVA_VM_VERSION + ", "
            + SystemUtils.JAVA_VM_INFO + ">");
    LOGGER.info("VM-ARGS: " + ManagementFactory.getRuntimeMXBean().getInputArguments());
    if (VersionRetriever.isLocalInfoAvailable()) {
        LOGGER.info("SKADI:   " + VersionRetriever.getLocalVersion() + " " + VersionRetriever.getLocalBuild()
                + " " + VersionRetriever.getLocalTimestamp());
    } else {
        LOGGER.info("SKADI:   " + "No local version info available");
    }
    LOGGER.info("ARGS:    " + Arrays.asList(args));
    LOGGER.info("################################################################################");
}

From source file:psiprobe.controllers.DecoratorController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    try {/*w w  w  . jav a 2s  .c  o m*/
        request.setAttribute("hostname", InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        request.setAttribute("hostname", "unknown");
        logger.trace("", e);
    }

    Properties version = (Properties) getApplicationContext().getBean("version");
    request.setAttribute("version", version.getProperty("probe.version"));

    long uptimeStartValue = ManagementFactory.getRuntimeMXBean().getStartTime();
    long uptime = System.currentTimeMillis() - uptimeStartValue;
    long uptimeDays = uptime / (1000 * 60 * 60 * 24);

    uptime = uptime % (1000 * 60 * 60 * 24);
    long uptimeHours = uptime / (1000 * 60 * 60);

    uptime = uptime % (1000 * 60 * 60);
    long uptimeMins = uptime / (1000 * 60);

    request.setAttribute("uptime_days", uptimeDays);
    request.setAttribute("uptime_hours", uptimeHours);
    request.setAttribute("uptime_mins", uptimeMins);
    //
    // Work out the language of the interface by matching resource files that we have
    // to the request locale.
    //
    String lang = "en";
    for (String fileName : getMessageFileNamesForLocale(request.getLocale())) {
        if (getServletContext().getResource(fileName + ".properties") != null) {
            lang = fileName.substring(messagesBasename.length() + 1);
            break;
        }
    }

    request.setAttribute("lang", lang);

    return super.handleRequestInternal(request, response);
}

From source file:com.hp.mqm.atrf.Main.java

private static void configureLog4J() {

    //set process Id on local
    RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
    String pid = rt.getName();//from  ww w. j  a  v  a2s .co  m
    ThreadContext.put("PID", pid);

    String log4jConfiguration = System.getProperty("log4j.configuration");
    if (StringUtils.isEmpty(log4jConfiguration)) {
        //try to take from file
        File f = new File("log4j2.xml");
        URI uri = null;
        if (f.exists() && !f.isDirectory() && f.canRead()) {
            uri = f.toURI();
        } else {
            //take it from resources
            try {
                uri = Main.class.getClassLoader().getResource("log4j2.xml").toURI();
            } catch (URISyntaxException e) {
                logger.info("Failed to load Log4j configuration from resource file");
            }
        }

        LoggerContext context = (LoggerContext) LogManager.getContext(false);
        context.setConfigLocation(uri);
        //logger.info("Log4j configuration loaded from " + uri.toString());
    } else {
        logger.info("Log4j configuration is loading from log4j.configuration=" + log4jConfiguration);
    }
}

From source file:org.apache.hadoop.hbase.io.TestHeapSize.java

@BeforeClass
public static void beforeClass() throws Exception {
    // Print detail on jvm so we know what is different should below test fail.
    RuntimeMXBean b = ManagementFactory.getRuntimeMXBean();
    LOG.info("name=" + b.getName());
    LOG.info("specname=" + b.getSpecName());
    LOG.info("specvendor=" + b.getSpecVendor());
    LOG.info("vmname=" + b.getVmName());
    LOG.info("vmversion=" + b.getVmVersion());
    LOG.info("vmvendor=" + b.getVmVendor());
    Map<String, String> p = b.getSystemProperties();
    LOG.info("properties=" + p);
}

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

/**
 * @return the setting of -XX:MaxDirectMemorySize as a long. Returns 0 if
 *         -XX:MaxDirectMemorySize is not set.
 *///from  w w  w  .  j a v  a  2s .c  o m
public static long getDirectMemorySize() {
    RuntimeMXBean runtimemxBean = ManagementFactory.getRuntimeMXBean();
    List<String> arguments = runtimemxBean.getInputArguments();
    long multiplier = 1; //for the byte case.
    for (String s : arguments) {
        if (s.contains("-XX:MaxDirectMemorySize=")) {
            String memSize = s.toLowerCase().replace("-xx:maxdirectmemorysize=", "").trim();

            if (memSize.contains("k")) {
                multiplier = 1024;
            }

            else if (memSize.contains("m")) {
                multiplier = 1048576;
            }

            else if (memSize.contains("g")) {
                multiplier = 1073741824;
            }
            memSize = memSize.replaceAll("[^\\d]", "");

            long retValue = Long.parseLong(memSize);
            return retValue * multiplier;
        }
    }
    return 0;
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.JvmMetricSet.java

public JvmMetricSet() {
    this.runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    Map<String, Metric> metricsByNames = new HashMap<>();

    this.bufferPoolMetricSet = new BufferPoolMetricSet();
    metricsByNames.put("bufferPools", bufferPoolMetricSet);

    this.classLoadingMetricSet = new ClassLoadingMetricSet();
    metricsByNames.put("classes", classLoadingMetricSet);

    this.threadMetricSet = new ThreadMetricSet();
    metricsByNames.put("threads", threadMetricSet);

    this.memoryMetricSet = new JvmMemoryMetricSet();
    metricsByNames.put("memory", memoryMetricSet);

    this.gcMetricSet = new GarbageCollectorMetricSet();
    metricsByNames.put("gc", gcMetricSet);

    this.uptimeInMillisGauge = new Gauge<Long>() {
        @Override//from  w  ww  .  ja  v a2 s. co  m
        public Long getValue() {
            return runtimeMXBean.getUptime();
        }
    };
    metricsByNames.put("uptimeInMillis", uptimeInMillisGauge);

    this.metricsByNames = metricsByNames;

    this.shutdown = new AtomicBoolean(false);
}

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

/**
 * Constructor for TelnetServer./*w ww.jav a 2 s .  c  o  m*/
 */
public TelnetServer() {
    _commands.add(new TelnetCommand("version", "ver") {
        @Override
        public String getUsage() {
            return "version";
        }

        @Override
        public String handle(String[] args) {
            return "Rev." + GameServer.getInstance().getVersion().getRevisionNumber() + " Builded : "
                    + GameServer.getInstance().getVersion().getBuildDate() + "\n";
        }
    });
    _commands.add(new TelnetCommand("uptime") {
        @Override
        public String getUsage() {
            return "uptime";
        }

        @Override
        public String handle(String[] args) {
            return DurationFormatUtils.formatDurationHMS(ManagementFactory.getRuntimeMXBean().getUptime())
                    + "\n";
        }
    });
    _commands.add(new TelnetCommand("restart") {
        @Override
        public String getUsage() {
            return "restart <seconds>|now>";
        }

        @Override
        public String handle(String[] args) {
            if (args.length == 0) {
                return null;
            }
            StringBuilder sb = new StringBuilder();
            if (NumberUtils.isNumber(args[0])) {
                int val = NumberUtils.toInt(args[0]);
                Shutdown.getInstance().schedule(val, Shutdown.RESTART);
                sb.append("Server will restart in ").append(Shutdown.getInstance().getSeconds())
                        .append(" seconds!\n");
                sb.append("Type \"abort\" to abort restart!\n");
            } else if (args[0].equalsIgnoreCase("now")) {
                sb.append("Server will restart now!\n");
                Shutdown.getInstance().schedule(0, Shutdown.RESTART);
            } else {
                String[] hhmm = args[0].split(":");
                Calendar date = Calendar.getInstance();
                Calendar now = Calendar.getInstance();
                date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hhmm[0]));
                date.set(Calendar.MINUTE, hhmm.length > 1 ? Integer.parseInt(hhmm[1]) : 0);
                date.set(Calendar.SECOND, 0);
                date.set(Calendar.MILLISECOND, 0);
                if (date.before(now)) {
                    date.roll(Calendar.DAY_OF_MONTH, true);
                }
                int seconds = (int) ((date.getTimeInMillis() / 1000L) - (now.getTimeInMillis() / 1000L));
                Shutdown.getInstance().schedule(seconds, Shutdown.RESTART);
                sb.append("Server will restart in ").append(Shutdown.getInstance().getSeconds())
                        .append(" seconds!\n");
                sb.append("Type \"abort\" to abort restart!\n");
            }
            return sb.toString();
        }
    });
    _commands.add(new TelnetCommand("shutdown") {
        @Override
        public String getUsage() {
            return "shutdown <seconds>|now|<hh:mm>";
        }

        @Override
        public String handle(String[] args) {
            if (args.length == 0) {
                return null;
            }
            StringBuilder sb = new StringBuilder();
            if (NumberUtils.isNumber(args[0])) {
                int val = NumberUtils.toInt(args[0]);
                Shutdown.getInstance().schedule(val, Shutdown.SHUTDOWN);
                sb.append("Server will shutdown in ").append(Shutdown.getInstance().getSeconds())
                        .append(" seconds!\n");
                sb.append("Type \"abort\" to abort shutdown!\n");
            } else if (args[0].equalsIgnoreCase("now")) {
                sb.append("Server will shutdown now!\n");
                Shutdown.getInstance().schedule(0, Shutdown.SHUTDOWN);
            } else {
                String[] hhmm = args[0].split(":");
                Calendar date = Calendar.getInstance();
                Calendar now = Calendar.getInstance();
                date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hhmm[0]));
                date.set(Calendar.MINUTE, hhmm.length > 1 ? Integer.parseInt(hhmm[1]) : 0);
                date.set(Calendar.SECOND, 0);
                date.set(Calendar.MILLISECOND, 0);
                if (date.before(now)) {
                    date.roll(Calendar.DAY_OF_MONTH, true);
                }
                int seconds = (int) ((date.getTimeInMillis() / 1000L) - (now.getTimeInMillis() / 1000L));
                Shutdown.getInstance().schedule(seconds, Shutdown.SHUTDOWN);
                sb.append("Server will shutdown in ").append(Shutdown.getInstance().getSeconds())
                        .append(" seconds!\n");
                sb.append("Type \"abort\" to abort shutdown!\n");
            }
            return sb.toString();
        }
    });
    _commands.add(new TelnetCommand("abort") {
        @Override
        public String getUsage() {
            return "abort";
        }

        @Override
        public String handle(String[] args) {
            Shutdown.getInstance().cancel();
            return "Aborted.\n";
        }
    });
}

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);/*  www  .  ja  va  2 s  . c  o m*/

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

    return b;
}

From source file:com.couchrqs.Queue.java

public Queue(Server couchDB, String name) {
    db = new Database(couchDB, name);
    visibilityTimeout = DEFAULT_VISIBILITY_TIMEOUT;
    processId = ManagementFactory.getRuntimeMXBean().getName();
}

From source file:com.dinstone.jrpc.spring.EndpointBeanDefinitionParser.java

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    String id = element.getAttribute("id");
    if (!StringUtils.hasText(id)) {
        id = endpointClass.getSimpleName() + "-" + count.incrementAndGet();
        builder.addPropertyValue("id", id);
        element.setAttribute("id", id);
    } else {//from  www . j  a  v a  2 s.  com
        builder.addPropertyValue("id", id);
    }

    String name = element.getAttribute("name");
    if (!StringUtils.hasText(name)) {
        String[] pidName = ManagementFactory.getRuntimeMXBean().getName().split("@");
        builder.addPropertyValue("name", pidName[1] + ":" + pidName[0]);
    } else {
        builder.addPropertyValue("name", name);
    }

    builder.addPropertyValue("transportBean", getConfigBeanDefinition(element, parserContext, "transport"));

    builder.addPropertyValue("registryBean", getConfigBeanDefinition(element, parserContext, "registry"));
}