Java Code Examples for java.lang.management.RuntimeMXBean

The following are top voted examples for showing how to use java.lang.management.RuntimeMXBean. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cdep   File: CDep.java   Source Code and License 8 votes vote down vote up
private boolean handleStartupInfo(@NotNull List<String> args) {
  if (args.size() > 0 && "startup-info".equals(args.get(0))) {
    String jvmLocation = API.getJvmLocation();
    infoln("%s", jvmLocation);
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
    List<String> jvmArgs = bean.getInputArguments();

    for (String jvmArg : jvmArgs) {
      infoln(jvmArg);
    }
    infoln("-classpath " + System.getProperty("java.class.path"));
    // print the non-JVM command line arguments
    // print name of the main class with its arguments, like org.ClassName param1 param2
    infoln(System.getProperty("sun.java.command"));
    return true;
  }
  return false;
}
 
Example 2
Project: sstable-adaptor   File: HeapUtils.java   Source Code and License 7 votes vote down vote up
/**
 * Retrieves the value of the <code>HeapDumpPath</code> JVM option.
 * @return the value of the <code>HeapDumpPath</code> JVM option or <code>null</code> if the value has not been
 * specified.
 */
private static String getHeapDumpPathOption()
{
    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    List<String> inputArguments = runtimeMxBean.getInputArguments();
    String heapDumpPathOption = null;
    for (String argument : inputArguments)
    {
        if (argument.startsWith("-XX:HeapDumpPath="))
        {
            heapDumpPathOption = argument;
            // We do not break in case the option has been specified several times.
            // In general it seems that JVMs use the right-most argument as the winner.
        }
    }

    if (heapDumpPathOption == null)
        return null;

    return heapDumpPathOption.substring(17, heapDumpPathOption.length());
}
 
Example 3
Project: incubator-netbeans   File: InternalSampler.java   Source Code and License 6 votes vote down vote up
private static synchronized boolean isDebugged() {
    if (debugMode == null) {
        debugMode = Boolean.FALSE;

        // check if we are debugged
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        List<String> args = runtime.getInputArguments();
        if (args.contains(X_DEBUG_ARG)) {
            debugMode = Boolean.TRUE;
        } else if (args.contains(JDWP_DEBUG_ARG)) {
            debugMode = Boolean.TRUE;
        } else {
            for (String arg : args) {
                if (arg.startsWith(JDWP_DEBUG_ARG_PREFIX)) {
                    debugMode = Boolean.TRUE;
                    break;
                }
            }
        }
    }
    return debugMode.booleanValue();
}
 
Example 4
Project: incubator-netbeans   File: MiscUtils.java   Source Code and License 6 votes vote down vote up
private static boolean checkIfDebugged() {
    try {
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        List<String> args = runtime.getInputArguments();
        for (String arg : args) {
            if ("-Xdebug".equals(arg)) { // NOI18N
                return true;                        
            } else if ("-agentlib:jdwp".equals(arg)) { // NOI18N
                // The idea of checking -agentlib:jdwp 
                // is taken from org.netbeans.modules.sampler.InternalSampler
                return true;
            } else if (arg.startsWith("-agentlib:jdwp=")) { // NOI18N
                return true;
            }
        }
    } catch (SecurityException ex) {                
    }
    return false;
}
 
Example 5
Project: JRediClients   File: RedissonTestRunListener.java   Source Code and License 6 votes vote down vote up
@Override
public void testRunStarted(Description description) throws Exception {
    super.testRunStarted(description);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        running.set(Boolean.FALSE);
    }));
    new Thread(() -> {
        final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        final AtomicLong u = new AtomicLong(runtimeBean.getUptime());
        while (running.get()) {
            try {
                long upTime = runtimeBean.getUptime();
                if (upTime >= u.get() + 10000) {
                    u.set(upTime);
                    System.out.printf("Test Up Time    = %.3f (s)%n", upTime / 1000d);
                    System.out.printf("Heap Usage      = %.3f (MB)%n", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024d / 1024d);
                    System.out.printf("None Heap Usage = %.3f (MB)%n", ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed() / 1024d / 1024d);
                    System.out.println("=============================");
                }
                Thread.currentThread().sleep(10000l);
            } catch (InterruptedException ex) {
                Logger.getLogger(RedissonTestRunListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }).start();
}
 
Example 6
Project: chimera   File: SysDeployer.java   Source Code and License 6 votes vote down vote up
public void start() throws Exception
{
    ConfigurableEnvironment ce = (ConfigurableEnvironment) applicationContext.getEnvironment();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    String jvmName = runtimeBean.getName();
    long pid = Long.valueOf(jvmName.split("@")[0]);

    final File tmpDir = new File(".", ".tmp_" + pid);
    if (tmpDir.exists())
    {
        deleteRecursive(tmpDir);
    }

    //noinspection ResultOfMethodCallIgnored
    tmpDir.mkdir();

    Runtime.getRuntime().addShutdownHook(new Thread(this::stop));

    baseDir = tmpDir.getAbsolutePath();
    PropertyResolver resolver = new SpringPropertyResolver(ce);
    resolver.initialize();

    deployer = ResourceDeployer.newInstance(resolver, tmpDir);
    deployer.installRuntimeResources();
    deployer.startConfigMonitoring();
}
 
Example 7
Project: cornerstone   File: AppInfo.java   Source Code and License 6 votes vote down vote up
@Override
public void refresh() {
    if(HostInfo.isTomcat()){
        webInfo = "view";
    }
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    upTime = runtimeBean.getUptime();
    EnApp enApp = EnFactory.getEnApp();
    enApp.refresh();
    appid = nullToNA(EnFactory.getEnBase().getAppId());
    appName = nullToNA(enApp.getName());
    appChineseName = nullToNA(enApp.getChineseName());
    appOwner = nullToNA(enApp.getOwner());
    appOwnerEmail = nullToNA(enApp.getOwnerContact());
    appBackup = nullToNA(enApp.getBackup());
    appVersion = nullToNA(enApp.getVersion());
    buildTime = nullToNA(enApp.getBuildTime());
    getStatus();
}
 
Example 8
Project: mycat-src-1.6.1-RELEASE   File: EnvironmentInformation.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the system parameters and environment parameters that were passed to the JVM on startup.
 *
 * @return The options passed to the JVM on startup.
 */
public static String getJvmStartupOptions() {
	try {
		final RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
		final StringBuilder bld = new StringBuilder();
		
		for (String s : bean.getInputArguments()) {
			bld.append(s).append(' ');
		}

		return bld.toString();
	}
	catch (Throwable t) {
		return UNKNOWN;
	}
}
 
Example 9
Project: log4j-aws-appenders   File: Substitutions.java   Source Code and License 6 votes vote down vote up
public Substitutions(Date currentDate, int sequence)
{
    RuntimeMXBean runtimeMx = ManagementFactory.getRuntimeMXBean();
    String vmName = runtimeMx.getName();

    pid = (vmName.indexOf('@') > 0)
        ? vmName.substring(0, vmName.indexOf('@'))
        : "unknown";

    hostname = (vmName.indexOf('@') > 0)
             ? vmName.substring(vmName.indexOf('@') + 1, vmName.length())
             : "unknown";

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    date = dateFormat.format(currentDate);

    SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    timestampFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    timestamp = timestampFormat.format(currentDate);
    hourlyTimestamp = timestamp.substring(0, 10) + "0000";  // yeah, it's a hack
    startupTimestamp = timestampFormat.format(new Date(runtimeMx.getStartTime()));

    this.sequence = String.valueOf(sequence);
}
 
Example 10
Project: flume-release-1.7.0   File: DirectMemoryUtils.java   Source Code and License 6 votes vote down vote up
public static long getDirectMemorySize() {
  RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
  List<String> arguments = Lists.reverse(RuntimemxBean.getInputArguments());
  long multiplier = 1; //for the byte case.
  for (String s : arguments) {
    if (s.contains(MAX_DIRECT_MEMORY_PARAM)) {
      String memSize = s.toLowerCase(Locale.ENGLISH)
          .replace(MAX_DIRECT_MEMORY_PARAM.toLowerCase(Locale.ENGLISH), "").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 DEFAULT_SIZE;
}
 
Example 11
Project: hawkular-java-toolbox   File: CPUMonitoring.java   Source Code and License 6 votes vote down vote up
private Optional<Double> reportCPU(OperatingSystemMXBean operatingSystemMXBean, RuntimeMXBean runtimeMXBean) {
    int availableProcessors = divideByNbCores ? operatingSystemMXBean.getAvailableProcessors() : 1;
    long upTime = runtimeMXBean.getUptime();
    long processCpuTime = operatingSystemMXBean.getProcessCpuTime();

    if (lastMeasures == null
            || lastMeasures.availableProcessors != availableProcessors
            || lastMeasures.processCpuTime < 0) {
        lastMeasures = new Measures(availableProcessors, upTime, processCpuTime);
        return Optional.empty();
    }

    long elapsedCpu = processCpuTime - lastMeasures.processCpuTime;
    long elapsedTime = upTime - lastMeasures.upTime;
    lastMeasures = new Measures(availableProcessors, upTime, processCpuTime);

    return Optional.of(Math.min(99D, elapsedCpu / (elapsedTime * 10000D * availableProcessors)));
}
 
Example 12
Project: validator-web   File: FileJavaScriptHandler.java   Source Code and License 6 votes vote down vote up
@Override
protected long getLastModifiedTime() {
    try {
        URL url = ResourceUtils.getResourceAsUrl(resource);
        if ("file".equals(url.getProtocol())) {
            File file = new File(url.getFile());
            return file.lastModified();
        }
    } catch (IOException ex) {
        // ignore
    }
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    long startTime = runtimeMXBean.getStartTime();
    // Container start time (browsers are only accurate to the second)
    return startTime - (startTime % 1000);
}
 
Example 13
Project: BaseClient   File: PlayerUsageSnooper.java   Source Code and License 6 votes vote down vote up
private void addJvmArgsToSnooper()
{
    RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean();
    List<String> list = runtimemxbean.getInputArguments();
    int i = 0;

    for (String s : list)
    {
        if (s.startsWith("-X"))
        {
            this.addClientStat("jvm_arg[" + i++ + "]", s);
        }
    }

    this.addClientStat("jvm_args", Integer.valueOf(i));
}
 
Example 14
Project: traccar-service   File: Log.java   Source Code and License 6 votes vote down vote up
public static void logSystemInfo() {
    try {
        OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();
        Log.info("Operating system"
                + " name: " + operatingSystemBean.getName()
                + " version: " + operatingSystemBean.getVersion()
                + " architecture: " + operatingSystemBean.getArch());

        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        Log.info("Java runtime"
                + " name: " + runtimeBean.getVmName()
                + " vendor: " + runtimeBean.getVmVendor()
                + " version: " + runtimeBean.getVmVersion());

        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        Log.info("Memory limit"
                + " heap: " + memoryBean.getHeapMemoryUsage().getMax() / (1024 * 1024) + "mb"
                + " non-heap: " + memoryBean.getNonHeapMemoryUsage().getMax() / (1024 * 1024) + "mb");

        Log.info("Character encoding: "
                + System.getProperty("file.encoding") + " charset: " + Charset.defaultCharset());

    } catch (Exception error) {
        Log.warning("Failed to get system info");
    }
}
 
Example 15
Project: OpenJSharp   File: JdpController.java   Source Code and License 6 votes vote down vote up
private static Integer getProcessId() {
    try {
        // Get the current process id using a reflection hack
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        Field jvm = runtime.getClass().getDeclaredField("jvm");
        jvm.setAccessible(true);

        VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
        Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
        pid_method.setAccessible(true);
        Integer pid = (Integer) pid_method.invoke(mgmt);
        return pid;
    } catch(Exception ex) {
        return null;
    }
}
 
Example 16
Project: monarch   File: ProcessManager.java   Source Code and License 6 votes vote down vote up
/**
 * Get the java agent passed to this process and pass it to the child VMs.
 * This was added to support jacoco code coverage reports
 */
private String getAgentString() {
  RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
  if (runtimeBean != null) {
    for(String arg: runtimeBean.getInputArguments()) {
      if(arg.contains("-javaagent:")) {
        //HACK for gradle bug  GRADLE-2859. Jacoco is passing a relative path
        //That won't work when we pass this to dunit VMs in a different
        //directory
        arg = arg.replace("-javaagent:..", "-javaagent:" + System.getProperty("user.dir") + File.separator + "src/main");
        arg = arg.replace("destfile=..", "destfile=" + System.getProperty("user.dir") + File.separator + "src/main");
        return arg;
      }
    }
  }

  return "-DdummyArg=true";
}
 
Example 17
Project: monarch   File: LocatorStatusResponse.java   Source Code and License 6 votes vote down vote up
public LocatorStatusResponse initialize(final int locatorPort, final String locatorHost,
    final String locatorLogFile, final String locatorName) {
  final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
  this.pid = identifyPid();
  this.jvmArgs = runtimeBean.getInputArguments();
  this.uptime = runtimeBean.getUptime();
  this.classpath = runtimeBean.getClassPath();
  this.gemfireVersion = GemFireVersion.getGemFireVersion();
  this.javaVersion = System.getProperty("java.version");
  this.workingDirectory = System.getProperty("user.dir");
  this.logFile = locatorLogFile;
  this.host = locatorHost;
  this.port = locatorPort;
  this.name = locatorName;
  return this;
}
 
Example 18
Project: dice   File: PersonalizationSource.java   Source Code and License 6 votes vote down vote up
private byte[] runtimeData() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    final Runtime rt = Runtime.getRuntime();

    bos.write(runtimeMXBean.getName().getBytes(StandardCharsets.UTF_8));
    bos.write(runtimeMXBean.getVmName().getBytes(StandardCharsets.UTF_8));
    bos.write(runtimeMXBean.getVmVendor().getBytes(StandardCharsets.UTF_8));
    bos.write(runtimeMXBean.getVmVersion().getBytes(StandardCharsets.UTF_8));
    bos.write(runtimeMXBean.getClassPath().getBytes(StandardCharsets.UTF_8));
    bos.write(ByteBuffer.allocate(Long.BYTES).putLong(runtimeMXBean.getStartTime()).array());

    bos.write(ByteBuffer.allocate(Long.BYTES).putLong(rt.totalMemory()).array());
    bos.write(ByteBuffer.allocate(Long.BYTES).putLong(rt.freeMemory()).array());

    return bos.toByteArray();
}
 
Example 19
Project: avaire   File: StatsCommand.java   Source Code and License 6 votes vote down vote up
private String applicationUptime() {
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
    long seconds = rb.getUptime() / 1000;
    long d = (long) Math.floor(seconds / 86400);
    long h = (long) Math.floor((seconds % 86400) / 3600);
    long m = (long) Math.floor(((seconds % 86400) % 3600) / 60);
    long s = (long) Math.floor(((seconds % 86400) % 3600) % 60);

    if (d > 0) {
        return String.format("%sd %sh %sm %ss", d, h, m, s);
    }

    if (h > 0) {
        return String.format("%sh %sm %ss", h, m, s);
    }

    if (m > 0) {
        return String.format("%sm %ss", m, s);
    }
    return String.format("%ss", s);
}
 
Example 20
Project: jdk8u-jdk   File: JdpController.java   Source Code and License 6 votes vote down vote up
private static Integer getProcessId() {
    try {
        // Get the current process id using a reflection hack
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        Field jvm = runtime.getClass().getDeclaredField("jvm");
        jvm.setAccessible(true);

        VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
        Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
        pid_method.setAccessible(true);
        Integer pid = (Integer) pid_method.invoke(mgmt);
        return pid;
    } catch(Exception ex) {
        return null;
    }
}
 
Example 21
Project: jdk8u-jdk   File: TestManager.java   Source Code and License 6 votes vote down vote up
private static void connect(String pid, String address) throws Exception {
    if (address == null) {
        throw new RuntimeException("Local connector address for " +
                                   pid + " is null");
    }

    System.out.println("Connect to process " + pid + " via: " + address);

    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector c = JMXConnectorFactory.connect(url);
    MBeanServerConnection server = c.getMBeanServerConnection();

    System.out.println("Connected.");

    RuntimeMXBean rt = newPlatformMXBeanProxy(server,
        RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    System.out.println(rt.getName());

    // close the connection
    c.close();
}
 
Example 22
Project: uavstack   File: JVMToolHelper.java   Source Code and License 6 votes vote down vote up
/**
 * obtain current process cpu utilization if jdk version is 1.6 by-hongqiangwei
 */
@SuppressWarnings("restriction")
public static double getProcessCpuUtilization() {

    com.sun.management.OperatingSystemMXBean osMBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    long processCpuTime1 = osMBean.getProcessCpuTime();
    long runtime1 = runtimeMXBean.getUptime();

    ThreadHelper.suspend(50);

    long processCpuTime2 = osMBean.getProcessCpuTime();
    long runtime2 = runtimeMXBean.getUptime();

    long deltaProcessTime = processCpuTime2 - processCpuTime1;
    long deltaRunTime = (runtime2 - runtime1) * 1000000L;
    int cpuNumber = Runtime.getRuntime().availableProcessors();
    double cpuUtilization = (double) deltaProcessTime / (deltaRunTime * cpuNumber);

    return cpuUtilization;
}
 
Example 23
Project: openjdk-jdk10   File: TestManager.java   Source Code and License 6 votes vote down vote up
private static void connect(String pid, String address) throws Exception {
    if (address == null) {
        throw new RuntimeException("Local connector address for " +
                                   pid + " is null");
    }

    System.out.println("Connect to process " + pid + " via: " + address);

    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector c = JMXConnectorFactory.connect(url);
    MBeanServerConnection server = c.getMBeanServerConnection();

    System.out.println("Connected.");

    RuntimeMXBean rt = newPlatformMXBeanProxy(server,
        RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    System.out.println(rt.getName());

    // close the connection
    c.close();
}
 
Example 24
Project: Backmemed   File: Snooper.java   Source Code and License 6 votes vote down vote up
private void addJvmArgsToSnooper()
{
    RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean();
    List<String> list = runtimemxbean.getInputArguments();
    int i = 0;

    for (String s : list)
    {
        if (s.startsWith("-X"))
        {
            this.addClientStat("jvm_arg[" + i++ + "]", s);
        }
    }

    this.addClientStat("jvm_args", Integer.valueOf(i));
}
 
Example 25
Project: swage   File: RuntimeSensor.java   Source Code and License 5 votes vote down vote up
@Override
public void sense(final MetricRecorder.Context metricContext)
{
    RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();

    metricContext.record(UPTIME, mxBean.getUptime(), Unit.MILLISECOND);
}
 
Example 26
Project: incubator-netbeans   File: Installer.java   Source Code and License 5 votes vote down vote up
static File getHeapDump() {
    String heapDumpPath = null;
    RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
    List<String> lst = RuntimemxBean.getInputArguments();
    for (String arg : lst) {
        if (arg.contains("XX:HeapDumpPath")){
            int index = arg.indexOf('=');
            heapDumpPath = arg.substring(index+1);
        }
    }

    if (heapDumpPath == null){
        LOG.info("XX:HeapDumpPath parametter not specified");
        return null;
    }
    File heapDumpFile = new File(heapDumpPath);
    if (heapDumpFile.exists() && heapDumpFile.canRead() && heapDumpFile.length() > 0) {
        return heapDumpFile;
    }
    LOG.log(Level.INFO, "heap dump was not created at {0}", heapDumpPath);
    LOG.log(Level.INFO, "heapdump file: exists():{0}, canRead():{1}, length:{2}",new Object[] 
            {heapDumpFile.exists(), heapDumpFile.canRead(), heapDumpFile.length()});
    // no heap dump file found - this can happen in case of OOME: unable to create new native thread
    // try to create heap dump 
    dumpHeap(heapDumpFile.getAbsolutePath());
    if (heapDumpFile.exists() && heapDumpFile.canRead() && heapDumpFile.length() > 0) {
        return heapDumpFile;
    }        
    LOG.log(Level.INFO, "heap dump failed for {0}", heapDumpPath);
    return null;
}
 
Example 27
Project: marathonv5   File: JavaServer.java   Source Code and License 5 votes vote down vote up
public JSONObject getInfo(JSONObject query, JSONObject uriParams) {
    JSONObject v = new JSONObject();
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
    v.put("boot-class-path", bean.getBootClassPath());
    v.put("start-time", bean.getStartTime());
    v.put("commandline", System.getProperty("sun.java.command"));
    return v;
}
 
Example 28
Project: marathonv5   File: JavaServer.java   Source Code and License 5 votes vote down vote up
public JSONObject getInfo(JSONObject query, JSONObject uriParams) {
    JSONObject v = new JSONObject();
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
    v.put("boot-class-path", bean.getBootClassPath());
    v.put("start-time", bean.getStartTime());
    v.put("commandline", System.getProperty("sun.java.command"));
    return v;
}
 
Example 29
Project: EatDubbo   File: ConfigUtils.java   Source Code and License 5 votes vote down vote up
public static int getPid() {
    if (PID < 0) {
        try {
            RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();  
            String name = runtime.getName(); // format: "[email protected]"  
            PID = Integer.parseInt(name.substring(0, name.indexOf('@')));
        } catch (Throwable e) {
            PID = 0;
        }
    }
    return PID;  
}
 
Example 30
Project: opencron   File: Bootstrap.java   Source Code and License 5 votes vote down vote up
private static Integer getPid() {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    String name = runtime.getName();
    try {
        return Integer.parseInt(name.substring(0, name.indexOf('@')));
    } catch (Exception e) {
    }
    return -1;
}
 
Example 31
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: UtilAll.java   Source Code and License 5 votes vote down vote up
public static int getPid() {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    String name = runtime.getName(); // format: "[email protected]"
    try {
        return Integer.parseInt(name.substring(0, name.indexOf('@')));
    } catch (Exception e) {
        return -1;
    }
}
 
Example 32
Project: mycat-src-1.6.1-RELEASE   File: EnvironmentInformation.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the version of the JVM in the form "VM_Name - Vendor  - Spec/Version".
 *
 * @return The JVM version.
 */
public static String getJvmVersion() {
	try {
		final RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
		return bean.getVmName() + " - " + bean.getVmVendor() + " - " + bean.getSpecVersion() + '/' + bean.getVmVersion();
	}
	catch (Throwable t) {
		return UNKNOWN;
	}
}
 
Example 33
Project: mycat-src-1.6.1-RELEASE   File: EnvironmentInformation.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the system parameters and environment parameters that were passed to the JVM on startup.
 *
 * @return The options passed to the JVM on startup.
 */
public static String[] getJvmStartupOptionsArray() {
	try {
		RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
		List<String> options = bean.getInputArguments();
		return options.toArray(new String[options.size()]);
	}
	catch (Throwable t) {
		return new String[0];
	}
}
 
Example 34
Project: cljbuck   File: Event.java   Source Code and License 5 votes vote down vote up
public static JsonKeyPair uptime() {
    final RuntimeMXBean mgmt = ManagementFactory.getRuntimeMXBean();
    return jsonPair()
            .add(NAME, "java -jar")
            .add(TIMESTAMP, mgmt.getStartTime() * 1000)
            .add(EVENT_TYPE, COMPLETE)
            .add(THREAD_ID, Thread.currentThread().getId())
            .add(DURATION, mgmt.getUptime() * 1000)
            .add(PROCESS_ID, 0);
}
 
Example 35
Project: ditb   File: ServerCommandLine.java   Source Code and License 5 votes vote down vote up
/**
 * Log information about the currently running JVM.
 */
public static void logJVMInfo() {
  // Print out vm stats before starting up.
  RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
  if (runtime != null) {
    LOG.info("vmName=" + runtime.getVmName() + ", vmVendor=" +
             runtime.getVmVendor() + ", vmVersion=" + runtime.getVmVersion());
    LOG.info("vmInputArguments=" + runtime.getInputArguments());
  }
}
 
Example 36
Project: java-memory-assistant   File: MBeanMonitor.java   Source Code and License 5 votes vote down vote up
JavaVirtualMachine findCurrentJvm()
    throws JavaVirtualMachine.UnsupportedJavaVirtualMachineException {
  final RuntimeMXBean runtimeBean = getRuntimeMxBean();
  final String specVendor = runtimeBean.getSpecVendor();
  final String specVersion = runtimeBean.getSpecVersion();
  final String vmVendor = runtimeBean.getVmVendor();
  final String vmVersion = runtimeBean.getVmVersion();

  logger.debug("JVM spec vendor: '%s'; spec version: '%s'; vm vendor: '%s'; vm version: '%s'",
      specVendor, specVersion, vmVendor, vmVersion);

  return JavaVirtualMachine.Supported.find(vmVendor, specVersion);
}
 
Example 37
Project: log4j-aws-appenders   File: TestSubstitutions.java   Source Code and License 5 votes vote down vote up
@Test
public void testStartupTimestamp() throws Exception
{
    Substitutions subs = new Substitutions(TEST_DATE, 0);

    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    String expected = formatter.format(new Date(runtimeMxBean.getStartTime()));

    assertEquals(expected, subs.perform("{startupTimestamp}"));
}
 
Example 38
Project: dubbo2   File: ConfigUtils.java   Source Code and License 5 votes vote down vote up
public static int getPid() {
    if (PID < 0) {
        try {
            RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();  
            String name = runtime.getName(); // format: "[email protected]"  
            PID = Integer.parseInt(name.substring(0, name.indexOf('@')));
        } catch (Throwable e) {
            PID = 0;
        }
    }
    return PID;  
}
 
Example 39
Project: reading-and-annotate-rocketmq-3.4.6   File: UtilAll.java   Source Code and License 5 votes vote down vote up
public static int getPid() {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    String name = runtime.getName(); // format: "[email protected]"
    try {
        return Integer.parseInt(name.substring(0, name.indexOf('@')));
    }
    catch (Exception e) {
        return -1;
    }
}
 
Example 40
Project: Saber-Bot   File: StatsCommand.java   Source Code and License 5 votes vote down vote up
@Override
public void action(String prefix, String[] args, MessageReceivedEvent event)
{
    JDA.ShardInfo info = event.getJDA().getShardInfo();
    Runtime rt = Runtime.getRuntime();
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();

    String msg = "```python\n" +
            "\"Database\"\n" +
            "      Entries: " + Main.getDBDriver().getEventCollection().count() + "\n" +
            "    Schedules: " + Main.getDBDriver().getScheduleCollection().count() + "\n" +
            "       Guilds: " + Main.getDBDriver().getGuildCollection().count() + "\n" +
            "\n\"Shard\"\n" +
            "      ShardId: " + info.getShardId() + "/" + info.getShardTotal() + "\n" +
            "       Guilds: " + event.getJDA().getGuilds().size() + "\n" +
            "        Users: " + event.getJDA().getUsers().size() + "\n" +
            "ResponseTotal: " + event.getJDA().getResponseTotal() + "\n" +
            "\n\"Application\"\n" +
            " Memory-total: " +rt.totalMemory()/1024/1024 + " MB\n" +
            "       -free : " + rt.freeMemory()/1024/1024 + " MB\n" +
            "       -max  : " + rt.maxMemory()/1024/1024 + " MB\n" +
            "      Threads: " + Thread.activeCount() + "\n" +
            "       Uptime: " + rb.getUptime()/1000/60 + " minute(s)" +
            "```";

    if(event.isFromType(ChannelType.PRIVATE))
    {
        MessageUtilities.sendPrivateMsg( msg, event.getAuthor(), null );
    }
    else
    {
        MessageUtilities.sendMsg( msg, event.getTextChannel(), null );
    }
}
 
Example 41
Project: QDrill   File: DrillConfig.java   Source Code and License 5 votes vote down vote up
@VisibleForTesting
public DrillConfig(Config config, boolean enableServerConfigs) {
  super(config);
  logger.debug("Setting up DrillConfig object.");
  logger.trace("Given Config object is:\n{}",
               config.root().render(ConfigRenderOptions.defaults()));
  mapper = new ObjectMapper();

  if (enableServerConfigs) {
    SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule")
      .addDeserializer(LogicalExpression.class, new LogicalExpression.De(this))
      .addDeserializer(SchemaPath.class, new SchemaPath.De());

    mapper.registerModule(deserModule);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
    mapper.configure(Feature.ALLOW_COMMENTS, true);
    mapper.registerSubtypes(LogicalOperatorBase.getSubTypes(this));
    mapper.registerSubtypes(StoragePluginConfigBase.getSubTypes(this));
    mapper.registerSubtypes(FormatPluginConfigBase.getSubTypes(this));
  }

  RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
  this.startupArguments = ImmutableList.copyOf(bean.getInputArguments());
  logger.debug("DrillConfig object initialized.");
}
 
Example 42
Project: legendarybot   File: BotStatsCommands.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(MessageReceivedEvent event, String[] args) {
    EmbedBuilder eb = new EmbedBuilder();
    eb.setColor(Color.getHSBColor(217,65,0));
    eb.setAuthor("LegendaryBot Stats","https://github.com/greatman/legendarybot","https://cdn.discordapp.com/app-icons/267134720700186626/ba3e3856b551e0c425280571db7746ef.jpg");

    RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
    String uptime = DurationFormatUtils.formatDuration(mxBean.getUptime(), "d") + " days " + DurationFormatUtils.formatDuration(mxBean.getUptime()," HH:mm:ss");

    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();
    int mb = 1024*1024;


    eb.addField(":homes:Guilds", plugin.getGuildCount() + "",true);
    eb.addField(":busts_in_silhouette: Members", plugin.getMemberCount() + "", true);
    eb.addField(":notepad_spiral:Text Channels", plugin.getTextChannelCount() + "", true);
    eb.addField(":loudspeaker:Voice Channels", plugin.getVoiceChannelCount() + "", true);
    eb.addField("Legendary checks", plugin.getLegendaryCount() + "", true);
    eb.addField(":timer:Uptime", uptime, true);

    eb.addField(":computer:Memory", "U: " +plugin.getUsedRam() + "MB / M: " + runtime.maxMemory() / mb + "MB", true);
    eb.addField(":speaker:Audio connections", plugin.getAudioConnections() + "", true);

    eb.addField(":musical_note: Song Queue", plugin.getSongQueue() + "", true);

    eb.setColor(Color.BLUE);

    event.getChannel().sendMessage(eb.build()).queue();


}
 
Example 43
Project: https-github.com-apache-zookeeper   File: OSMXBean.java   Source Code and License 5 votes vote down vote up
/**
 * Get the number of opened filed descriptor for the runtime jvm.
 * If sun 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
 */
public long getOpenFileDescriptorCount() 
{
    Long ofdc;

    if (!ibmvendor) {
        ofdc = getOSUnixMXBeanMethod("getOpenFileDescriptorCount");
        return (ofdc != null ? ofdc.longValue () : -1);
    }
    
    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" });
        InputStream in = p.getInputStream();
        BufferedReader output = new BufferedReader(
                new InputStreamReader(in));

        try {
            String openFileDesCount;
            if ((openFileDesCount = output.readLine()) != null) {
                return Long.parseLong(openFileDesCount);
            }
        } finally {
            if (output != null) {
                output.close();
            }
        }
    } catch (IOException ie) {
        LOG.warn("Not able to get the number of open file descriptors", ie);
    }
    return -1;
}
 
Example 44
Project: jsf-sdk   File: JVMStatusTelnetHandler.java   Source Code and License 5 votes vote down vote up
@Override
   public String telnet(Channel channel, String message) {
	StringBuilder sb = new StringBuilder();
	//内存使用情况
       MemoryMXBean mmxb = ManagementFactory.getMemoryMXBean();
       long max = mmxb.getHeapMemoryUsage().getMax();
       long used = mmxb.getHeapMemoryUsage().getUsed();
       long init = mmxb.getHeapMemoryUsage().getInit();
       long commit = mmxb.getHeapMemoryUsage().getCommitted();
       sb.append("********Memory status******************").append(line);
       sb.append("Max JVM Heap Memory:").append(max / 1024 / 1024).append("M").append(line)
               .append("Used Heap Memory:").append(used / 1024 / 1024).append("M").append(line)
               .append("Init Heap Memory:").append(init / 1024 / 1024).append("M").append(line)
               .append("Commited Heap Memory:").append(commit/1024/1024).append("M").append(line);
       
       sb.append("********Thread status********************").append(line);
       //线程数
       ThreadMXBean txmb = ManagementFactory.getThreadMXBean();
       sb.append("Peak thread count:").append(txmb.getPeakThreadCount()).append("").append(line)
               .append("Thread count:").append(txmb.getThreadCount()).append("").append(line);

       sb.append("********Runtime status******************").append(line);
       //启动入口参数
       RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
       sb.append("InputArguments:[");
       for(String ia : rmxb.getInputArguments()){
       	sb.append(ia).append(",");
       }
       sb.deleteCharAt(sb.length()-1).append("]").append(line);
       sb.append("JVM start time:").append(DateUtils.dateToStr(new Date(rmxb.getStartTime()))).append(line);
       
       return sb.toString();
}
 
Example 45
Project: ditb   File: TestHeapSize.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 46
Project: monarch   File: LocalProcessController.java   Source Code and License 5 votes vote down vote up
/**
 * Ensures that the other process identifies itself by the same pid used by this stopper to
 * connect to that process. NOT USED EXCEPT IN TEST.
 * 
 * @return true if the pid matches
 * 
 * @throws IllegalStateException if the other process identifies itself by a different pid
 * @throws IOException if a communication problem occurred when accessing the
 *         MBeanServerConnection
 * @throws PidUnavailableException if parsing the pid from the RuntimeMXBean name fails
 */
boolean checkPidMatches() throws IllegalStateException, IOException, PidUnavailableException {
  final RuntimeMXBean proxy = ManagementFactory.newPlatformMXBeanProxy(this.server,
      ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
  final int remotePid = ProcessUtils.identifyPid(proxy.getName());
  if (remotePid != this.pid) {
    throw new IllegalStateException(
        "Process has different pid '" + remotePid + "' than expected pid '" + this.pid + "'");
  } else {
    return true;
  }
}
 
Example 47
Project: monarch   File: MBeanProcessController.java   Source Code and License 5 votes vote down vote up
/**
 * Ensures that the other process identifies itself by the same pid used by this stopper to
 * connect to that process. NOT USED EXCEPT IN TEST.
 * 
 * @return true if the pid matches
 * 
 * @throws IllegalStateException if the other process identifies itself by a different pid
 * @throws IOException if a communication problem occurred when accessing the
 *         MBeanServerConnection
 * @throws PidUnavailableException if parsing the pid from the RuntimeMXBean name fails
 */
boolean checkPidMatches() throws IllegalStateException, IOException, PidUnavailableException {
  final RuntimeMXBean proxy = ManagementFactory.newPlatformMXBeanProxy(this.server,
      ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
  final int remotePid = ProcessUtils.identifyPid(proxy.getName());
  if (remotePid != this.pid) {
    throw new IllegalStateException(
        "Process has different pid '" + remotePid + "' than expected pid '" + this.pid + "'");
  } else {
    return true;
  }
}
 
Example 48
Project: dubbox-hystrix   File: ConfigUtils.java   Source Code and License 5 votes vote down vote up
public static int getPid() {
    if (PID < 0) {
        try {
            RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();  
            String name = runtime.getName(); // format: "[email protected]"  
            PID = Integer.parseInt(name.substring(0, name.indexOf('@')));
        } catch (Throwable e) {
            PID = 0;
        }
    }
    return PID;  
}
 
Example 49
Project: ChronoBike   File: JmxClassPath.java   Source Code and License 5 votes vote down vote up
public static String getBootClassPath()
{
	RuntimeMXBean r = ManagementFactory.getRuntimeMXBean();
	if(r != null)
	{
		String cs = r.getBootClassPath();
		return cs;
	}
	return "";
}
 
Example 50
Project: ChronoBike   File: JmxClassPath.java   Source Code and License 5 votes vote down vote up
public static String getClassPath()
{
	RuntimeMXBean r = ManagementFactory.getRuntimeMXBean();
	if(r != null)
	{
		String cs = r.getClassPath();
		return cs;
	}
	return "";
}
 
Example 51
Project: ChronoBike   File: JmxClassPath.java   Source Code and License 5 votes vote down vote up
public static String getLibraryPath()
{
	RuntimeMXBean r = ManagementFactory.getRuntimeMXBean();
	if(r != null)
	{
		String cs = r.getLibraryPath();
		return cs;
	}
	return "";
}
 
Example 52
Project: ChronoBike   File: JmxClassPath.java   Source Code and License 5 votes vote down vote up
public static String getAllPaths()
{
	String cs = "";
	RuntimeMXBean r = ManagementFactory.getRuntimeMXBean();
	if(r != null)
	{
		cs = "ClassPath="+r.getClassPath();
		cs += "; BootClassPath="+r.getBootClassPath();
		cs += "; LibraryPath="+r.getLibraryPath();
		return cs;
	}
	return "";
}
 
Example 53
Project: MaxSim   File: TestMetaspaceMemoryPool.java   Source Code and License 5 votes vote down vote up
private static boolean isFlagDefined(String name) {
    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    List<String> args = runtimeMxBean.getInputArguments();
    for (String arg : args) {
        if (arg.startsWith("-XX:" + name)) {
            return true;
        }
    }
    return false;
}
 
Example 54
Project: MaxSim   File: Test7194254.java   Source Code and License 5 votes vote down vote up
static String getPid() {
    RuntimeMXBean runtimebean = ManagementFactory.getRuntimeMXBean();
    String vmname = runtimebean.getName();
    int i = vmname.indexOf('@');
    if (i != -1) {
        vmname = vmname.substring(0, i);
    }
    return vmname;
}
 
Example 55
Project: avaire   File: UptimeCommand.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onCommand(Message message, String[] args) {
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();

    Carbon time = Carbon.now().subSeconds(NumberUtil.parseInt("" + (rb.getUptime() / 1000)));

    MessageFactory.makeInfo(message, "I have been online for :time")
        .set("time", time.diffForHumans(true))
        .setFooter("Started " + time.format("EEEEEEEE, dd MMM yyyy") + " at " + time.format("HH:mm:ss z"))
        .queue();

    return true;
}
 
Example 56
Project: MFM   File: MFM.java   Source Code and License 5 votes vote down vote up
private static void logEnvironment() {
    logger.out("Temp dir is " + TEMP_DIR);

    // Get the VM arguments and log
    RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
    List<String> arguments = RuntimemxBean.getInputArguments();
    logger.separateLine();
    logger.out(OS_version + "\n");

    if (isDebug()) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            if (envName.contains("PROCESSOR")) {
                logger.out(envName + " : " + env.get(envName));
            }
        }
    }
    logger.separateLine();
    String JAVA_version = System.getProperty("java.version");
    String JVM_version = ManagementFactory.getRuntimeMXBean().getVmVersion();
    logger.addToList("Java version : " + JAVA_version);
    logger.addToList("JVM version : " + JVM_version);
    for (String arg : arguments) {
        logger.addToList(arg);
        if (arg.startsWith("-Xloggc:")) {
            GCLog = new File(arg.substring(arg.indexOf(':') + 1));
        }
    }
    logger.separateLine();
}
 
Example 57
Project: jsf-core   File: ScheduleServer.java   Source Code and License 5 votes vote down vote up
public static int getPid() {
    int PID = -1;
    if (PID < 0) {
        try {
            RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
            String name = runtime.getName(); // format: "[email protected]"
            PID = Integer.parseInt(name.substring(0, name.indexOf('@')));
        } catch (Throwable e) {
            PID = 0;
        }
    }
    return PID;
}
 
Example 58
Project: openjdk-jdk10   File: TestThreadDumpMonitorContention.java   Source Code and License 5 votes vote down vote up
static String getPid() {
    RuntimeMXBean runtimebean = ManagementFactory.getRuntimeMXBean();
    String vmname = runtimebean.getName();
    int i = vmname.indexOf('@');
    if (i != -1) {
        vmname = vmname.substring(0, i);
    }
    return vmname;
}
 
Example 59
Project: openjdk-jdk10   File: TransitionsTestExecutor.java   Source Code and License 5 votes vote down vote up
private static void executeTestFor(int compilationPolicy, String testName) throws Throwable {
    String policy = "-XX:CompilationPolicyChoice=" + compilationPolicy;

    // Get runtime arguments including VM options given to this executor
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    List<String> vmArgs = runtime.getInputArguments();

    // Construct execution command with compilation policy choice and test name
    List<String> args = new ArrayList<>(vmArgs);
    Collections.addAll(args, policy, testName);

    OutputAnalyzer out = ProcessTools.executeTestJvm(args.toArray(new String[args.size()]));
    out.shouldHaveExitValue(0);
}
 
Example 60
Project: ditb   File: DirectMemoryUtils.java   Source Code and License 5 votes vote down vote up
/**
 * @return the setting of -XX:MaxDirectMemorySize as a long. Returns 0 if
 *         -XX:MaxDirectMemorySize is not set.
 */
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;
}