java.lang.management.RuntimeMXBean Java Examples

The following examples show how to use java.lang.management.RuntimeMXBean. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestManager.java    From hottub with GNU General Public License v2.0 7 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 #2
Source File: TestManager.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 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 #3
Source File: AkServerUtil.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void printRuntimeInfo() {
    System.out.println();
    RuntimeMXBean m = java.lang.management.ManagementFactory
            .getRuntimeMXBean();
    System.out.println("BootClassPath = " + m.getBootClassPath());
    System.out.println("ClassPath = " + m.getClassPath());
    System.out.println("LibraryPath = " + m.getLibraryPath());
    System.out.println("ManagementSpecVersion = "
            + m.getManagementSpecVersion());
    System.out.println("Name = " + m.getName());
    System.out.println("SpecName = " + m.getSpecName());
    System.out.println("SpecVendor = " + m.getSpecVendor());
    System.out.println("SpecVersion = " + m.getSpecVersion());
    System.out.println("UpTime = " + m.getUptime());
    System.out.println("VmName = " + m.getVmName());
    System.out.println("VmVendor = " + m.getVmVendor());
    System.out.println("VmVersion = " + m.getVmVersion());
    System.out.println("InputArguments = " + m.getInputArguments());
    System.out.println("BootClassPathSupported = "
            + m.isBootClassPathSupported());
    System.out.println("---all properties--");
    System.out.println("SystemProperties = " + m.getSystemProperties());
    System.out.println("---");
    System.out.println();
}
 
Example #4
Source File: EnvironmentCreator.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static JavaInfo createJavaInfo(String glowrootVersion, JvmConfig jvmConfig,
        RuntimeMXBean runtimeMXBean) {
    String jvm = "";
    String javaVmName = StandardSystemProperty.JAVA_VM_NAME.value();
    if (javaVmName != null) {
        jvm = javaVmName + " (" + StandardSystemProperty.JAVA_VM_VERSION.value() + ", "
                + System.getProperty("java.vm.info") + ")";
    }
    String javaVersion = StandardSystemProperty.JAVA_VERSION.value();
    String heapDumpPath = getHeapDumpPathFromCommandLine();
    if (heapDumpPath == null) {
        String javaTempDir =
                MoreObjects.firstNonNull(StandardSystemProperty.JAVA_IO_TMPDIR.value(), ".");
        heapDumpPath = new File(javaTempDir).getAbsolutePath();
    }
    return JavaInfo.newBuilder()
            .setVersion(Strings.nullToEmpty(javaVersion))
            .setVm(jvm)
            .addAllArg(Masking.maskJvmArgs(runtimeMXBean.getInputArguments(),
                    jvmConfig.maskSystemProperties()))
            .setHeapDumpDefaultDir(heapDumpPath)
            .setGlowrootAgentVersion(glowrootVersion)
            .build();
}
 
Example #5
Source File: JRockitJvmProvider.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Jvm createModelFor(Application app) {
    Jvm jvm = null;
    JvmstatModel jvmstat = JvmstatModelFactory.getJvmstatFor(app);

    if (jvmstat != null) {
        String vmName = jvmstat.findByName(VM_NAME);
        if (JROCKIT_VM_NAME.equals(vmName)) {
            jvm = new JRockitJVMImpl(app, jvmstat);
        }
    } else {
        JmxModel jmxModel = JmxModelFactory.getJmxModelFor(app);
        if (jmxModel != null && jmxModel.getConnectionState() == JmxModel.ConnectionState.CONNECTED) {
            JvmMXBeans mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel);
            if (mxbeans != null) {
                RuntimeMXBean runtime = mxbeans.getRuntimeMXBean();
                if (runtime != null && JROCKIT_VM_NAME.equals(runtime.getVmName())) {
                    jvm = new JRockitJVMImpl(app);
                }
            }
        }
    }
    return jvm;
}
 
Example #6
Source File: RuntimeInformationProvider.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> asJson() {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    long uptime = runtimeMXBean.getUptime();
    long uptimeInSeconds = uptime / 1000;
    long numberOfHours = uptimeInSeconds / (60 * 60);
    long numberOfMinutes = (uptimeInSeconds / 60) - (numberOfHours * 60);
    long numberOfSeconds = uptimeInSeconds % 60;

    LinkedHashMap<String, Object> json = new LinkedHashMap<>();
    json.put("Name", runtimeMXBean.getName());
    json.put("Uptime", runtimeMXBean.getUptime());
    json.put("Uptime (in Time Format)", "[About " + numberOfHours + " hours, " + numberOfMinutes + " minutes, " + numberOfSeconds + " seconds]");
    json.put("Spec Name", runtimeMXBean.getSpecName());
    json.put("Spec Vendor", runtimeMXBean.getSpecVendor());
    json.put("Spec Version", runtimeMXBean.getSpecVersion());

    json.put("Input Arguments", runtimeMXBean.getInputArguments());
    json.put("System Properties", new TreeMap<>(asIndentedMultilineValuesAsJson(runtimeMXBean.getSystemProperties())));
    json.put("Environment Variables", new TreeMap<>(asIndentedMultilineValuesAsJson(System.getenv())));

    return json;
}
 
Example #7
Source File: EnvironmentInformation.java    From flink with Apache License 2.0 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 #8
Source File: MemoryTrainingListener.java    From djl with Apache License 2.0 6 votes vote down vote up
private static void getProcessInfo(Metrics metrics) {
    if (System.getProperty("os.name").startsWith("Linux")
            || System.getProperty("os.name").startsWith("Mac")) {
        // This solution only work for Linux like system.
        RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
        String pid = mxBean.getName().split("@")[0];
        String cmd = "ps -o %cpu= -o rss= -p " + pid;
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            try (InputStream is = process.getInputStream()) {
                String line = new String(readAll(is), StandardCharsets.UTF_8).trim();
                String[] tokens = line.split("\\s+");
                if (tokens.length != 2) {
                    logger.error("Invalid ps output: {}", line);
                    return;
                }
                float cpu = Float.parseFloat(tokens[0]);
                long rss = Long.parseLong(tokens[1]);
                metrics.addMetric("cpu", cpu, "%");
                metrics.addMetric("rss", rss, "KB");
            }
        } catch (IOException e) {
            logger.error("Failed execute cmd: " + cmd, e);
        }
    }
}
 
Example #9
Source File: JdpController.java    From jdk8u_jdk with GNU General Public License v2.0 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 #10
Source File: FileJavaScriptHandler.java    From validator-web with Apache License 2.0 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 #11
Source File: UptimeCommand.java    From vk-java-sdk with MIT License 6 votes vote down vote up
@Override
public void run() throws ClientException, ApiException {
    RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
    long uptime = mxBean.getUptime();

    String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(uptime),
            TimeUnit.MILLISECONDS.toMinutes(uptime) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(uptime)),
            TimeUnit.MILLISECONDS.toSeconds(uptime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(uptime)));

    String msg = "Uptime is " + hms + ".\n" +
            "Statistics: \n"
            + "Executed commands " + Statistic.get(Statistic.Event.COMMAND) + "\n"
            + "Failed commands " + Statistic.get(Statistic.Event.FAILED_COMMAND) + "\n"
            + "Loaded users " + YouTrackUsersStorage.getInstance().getCount();


    sendMessage(msg);
}
 
Example #12
Source File: Java6CpuLoadMetric.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public Java6CpuLoadMetric() {
    final OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    if (operatingSystemMXBean == null) {
        throw new IllegalStateException("OperatingSystemMXBean not available");
    }
    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    if (runtimeMXBean == null) {
        throw new IllegalStateException("RuntimeMXBean not available");
    }

    CpuUsageProvider jvmCpuUsageProvider = new JvmCpuUsageProvider(operatingSystemMXBean, runtimeMXBean);
    try {
        jvmCpuUsageProvider.getCpuUsage();
    } catch (NoSuchMethodError e) {
        logger.warn("Expected method not found for retrieving jvm cpu usage. Cause : {}", e.getMessage());
        jvmCpuUsageProvider = CpuUsageProvider.UNSUPPORTED;
    }
    this.jvmCpuUsageProvider = jvmCpuUsageProvider;
}
 
Example #13
Source File: JdpController.java    From jdk8u-jdk with GNU General Public License v2.0 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 #14
Source File: JVMToolHelper.java    From uavstack with Apache License 2.0 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 #15
Source File: DirectMemoryUtils.java    From mt-flume with Apache License 2.0 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()
          .replace(MAX_DIRECT_MEMORY_PARAM.toLowerCase(), "").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 #16
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Mimics Uptime metrics from Micrometer. Most of the logic here is basically copied from
 * {@link <a href=
 * "https://github.com/micrometer-metrics/micrometer/blob/master/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/UptimeMetrics.java">Micrometer
 * Uptime metrics</a>}.
 * 
 * @param registry
 */
private void micrometerRuntimeMetrics(MetricRegistry registry) {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("process.runtime")
                    .withType(MetricType.GAUGE)
                    .withUnit(MetricUnits.MILLISECONDS)
                    .withDescription("The uptime of the Java virtual machine")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return runtimeMXBean.getUptime();
                }
            });
    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("process.start.time")
                    .withType(MetricType.GAUGE)
                    .withUnit(MetricUnits.MILLISECONDS)
                    .withDescription("Start time of the process since unix epoch.")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return runtimeMXBean.getStartTime();
                }
            });
}
 
Example #17
Source File: ProcessInfo.java    From Mycat-openEP with Apache License 2.0 5 votes vote down vote up
private static void extractPID(){
	RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();  
       String name = runtime.getName(); // format: "pid@hostname"  
       try {  
           PID_TEXT=name.substring(0, name.indexOf('@'));  
       } catch (Exception e) {  
           PID_TEXT="-1";  
       }
}
 
Example #18
Source File: JavaPIDUtil.java    From xian with Apache License 2.0 5 votes vote down vote up
private static void initPID() {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    String name = runtime.getName();
    System.out.println("Java process name: " + name);
    PROCESS_NAME = name;
    int index = name.indexOf("@");
    if (index != -1) {
        PID = Integer.parseInt(name.substring(0, index));
        System.out.println("Java process id: " + PID);
        hostname = name.substring(index + 1);
        System.out.println("hostname: " + hostname);
    } else {
        throw new RuntimeException("Failed to obtain the java process id.");
    }
}
 
Example #19
Source File: ConfigUtils.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * 获取进程ID
 *
 * @author sxp
 * @since 2018/12/1
 */
public static int getPid() {
  if (PID < 0) {
    try {
      RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
      String name = runtime.getName(); // format: "pid@hostname"
      PID = Integer.parseInt(name.substring(0, name.indexOf('@')));
    } catch (Throwable e) {
      PID = 0;
    }
  }
  return PID;
}
 
Example #20
Source File: Bootstrap.java    From opencron with Apache License 2.0 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 #21
Source File: StandardExportsTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  osBean = mock(UnixOperatingSystemMXBean.class);
  when(osBean.getName()).thenReturn("Linux");
  when(osBean.getProcessCpuTime()).thenReturn(123L);
  when(osBean.getOpenFileDescriptorCount()).thenReturn(10L);
  when(osBean.getMaxFileDescriptorCount()).thenReturn(20L);
  runtimeBean = mock(RuntimeMXBean.class);
  when(runtimeBean.getStartTime()).thenReturn(456L);
}
 
Example #22
Source File: SystemPropertyInformation.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public String getSystemPropertyInformation() {

        final StringBuilder systemPropertyBuilder = new StringBuilder();
        final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();

        final Map<String, String> systemProperties = runtimeBean.getSystemProperties();
        final Set<String> keys = systemProperties.keySet();
        for (final String key : keys) {

            final String value = systemProperties.get(key);
            addInformation(systemPropertyBuilder, key, value);
        }

        return systemPropertyBuilder.toString();
    }
 
Example #23
Source File: ProcessTools.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the string containing input arguments passed to the VM
 *
 * @return arguments
 */
public static String getVmInputArguments() {
  RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();

  List<String> args = runtime.getInputArguments();
  StringBuilder result = new StringBuilder();
  for (String arg : args)
      result.append(arg).append(' ');

  return result.toString();
}
 
Example #24
Source File: ProdJmxConnect.java    From cassandra-mesos-deprecated with Apache License 2.0 5 votes vote down vote up
@NotNull
public RuntimeMXBean getRuntimeProxy() {
    if (runtimeProxy == null) {
        runtimeProxy = newPlatformProxy(ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    }
    return runtimeProxy;
}
 
Example #25
Source File: LocalProcessController.java    From gemfirexd-oss with Apache License 2.0 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 #26
Source File: TLCRuntime.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * @return The non-heap memory JVM memory set with -XX:MaxDirectMemorySize in Bytes
 */
public long getNonHeapPhysicalMemory() {
	// 64MB by default. This happens to be the JVM default for
	// XX:MaxDirectMemorySize if no other value is given.
	long l = (64L * 1024L * 1024L);
	
	final RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
	final List<String> arguments = RuntimemxBean.getInputArguments();
	for (String arg : arguments) {
		if (arg.toLowerCase().startsWith("-xx:maxdirectmemorysize")) {
			String[] strings = arg.split("=");
			String mem = strings[1].toLowerCase();
			if (mem.endsWith("g")) {
				l = Long.parseLong(mem.substring(0, mem.length() -1));
				l = l << 30;
				break;
			} else if (mem.endsWith("m")) {
				l = Long.parseLong(mem.substring(0, mem.length() -1));
				l = l << 20;
				break;
			} else if (mem.endsWith("k")) {
				l = Long.parseLong(mem.substring(0, mem.length() -1));
				l = l << 10;
				break;
			} else {
				l = Long.parseLong(mem.substring(0, mem.length()));
				break;
			}
		}
	}
	return l;
}
 
Example #27
Source File: HeisenbergStartup.java    From heisenberg with Apache License 2.0 5 votes vote down vote up
public static final int jvmPid() {
    try {
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        Field jvm = runtime.getClass().getDeclaredField("jvm");
        jvm.setAccessible(true);
        VMManagement mgmt = (VMManagement) jvm.get(runtime);
        Method pidMethod = mgmt.getClass().getDeclaredMethod("getProcessId");
        pidMethod.setAccessible(true);
        int pid = (Integer) pidMethod.invoke(mgmt);
        return pid;
    } catch (Exception e) {
        return -1;
    }
}
 
Example #28
Source File: UptimeSampler.java    From kieker with Apache License 2.0 5 votes vote down vote up
@Override
protected IMonitoringRecord[] createNewMonitoringRecords(final long timestamp, final String hostname, final String vmName,
		final IMonitoringController monitoringCtr) {
	if (!monitoringCtr.isProbeActivated(SignatureFactory.createJVMUpTimeSignature())) {
		return new IMonitoringRecord[] {};
	}

	final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();

	return new IMonitoringRecord[] { new UptimeRecord(timestamp, hostname, vmName, runtimeBean.getUptime()), };
}
 
Example #29
Source File: SystemInfoHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static List<String> getInputArgumentsRedacted(RuntimeMXBean mx) {
  List<String> list = new LinkedList<>();
  for (String arg : mx.getInputArguments()) {
    if (arg.startsWith("-D") && arg.contains("=") && RedactionUtils.isSystemPropertySensitive(arg.substring(2, arg.indexOf("=")))) {
      list.add(String.format(Locale.ROOT, "%s=%s", arg.substring(0, arg.indexOf("=")), REDACT_STRING));
    } else {
      list.add(arg);
    }
  }
  return list;
}
 
Example #30
Source File: SystemUtil.java    From xnx3 with Apache License 2.0 5 votes vote down vote up
/**
* 获取当前程序的pid(任务管理器里的pid)
* @return 成功,则返回该pid,若是失败、出错异常,则返回-1
*/
  public static int getPid() {
      RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
      String name = runtime.getName(); // format: "pid@hostname"
      try {
          return Integer.parseInt(name.substring(0, name.indexOf('@')));
      } catch (Exception e) {
          return -1;
      }
  }