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 Project: hottub   Author: dsrg-uoft   File: TestManager.java    License: 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 Project: flink   Author: apache   File: EnvironmentInformation.java    License: 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 #3
Source Project: djl   Author: awslabs   File: MemoryTrainingListener.java    License: 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 #4
Source Project: jdk8u-jdk   Author: frohoff   File: JdpController.java    License: 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 #5
Source Project: uavstack   Author: uavorg   File: JVMToolHelper.java    License: 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 #6
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: TestManager.java    License: 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 #7
Source Project: mt-flume   Author: javachen   File: DirectMemoryUtils.java    License: 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 #8
Source Project: gocd   Author: gocd   File: RuntimeInformationProvider.java    License: 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 #9
Source Project: glowroot   Author: glowroot   File: EnvironmentCreator.java    License: 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 #10
Source Project: sql-layer   Author: jaytaylor   File: AkServerUtil.java    License: 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 #11
Source Project: visualvm   Author: oracle   File: JRockitJvmProvider.java    License: 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 #12
Source Project: pinpoint   Author: naver   File: Java6CpuLoadMetric.java    License: 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 Project: jdk8u_jdk   Author: JetBrains   File: JdpController.java    License: 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 Project: vk-java-sdk   Author: VKCOM   File: UptimeCommand.java    License: 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 #15
Source Project: validator-web   Author: devefx   File: FileJavaScriptHandler.java    License: 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 #16
Source Project: grpc-nebula-java   Author: grpc-nebula   File: ConfigUtils.java    License: 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: "[email protected]"
      PID = Integer.parseInt(name.substring(0, name.indexOf('@')));
    } catch (Throwable e) {
      PID = 0;
    }
  }
  return PID;
}
 
Example #17
Source Project: tomee   Author: apache   File: ThreadStackRule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    if (System.getProperty("os.name", "unknown").toLowerCase().startsWith("windows")) {
        return base;
    }
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            final ScheduledExecutorService ses = Executors.newScheduledThreadPool(1, new DaemonThreadFactory(ThreadStackRule.class.getSimpleName() + "-"));
            final ScheduledFuture<?> task = ses.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    final RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

                    String pid = bean.getName();
                    if (pid.contains("@")) {
                        pid = pid.substring(0, pid.indexOf("@"));
                    }

                    try {
                        Pipe.pipe(Runtime.getRuntime().exec("kill -3 " + pid));
                    } catch (final Exception exception) {
                        exception.printStackTrace();
                    }
                }
            }, 2, 2, TimeUnit.MINUTES);
            try {
                base.evaluate();
            } finally {
                task.cancel(true);
                ses.shutdownNow();
            }
        }
    };
}
 
Example #18
Source Project: DDMQ   Author: didi   File: UtilAll.java    License: Apache License 2.0 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 #19
Source Project: Deta_Cache   Author: yaoguangluo   File: OperatingSystemInfoUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * ���� MXBean �ķ��������ַ���
	 */
	public static  Map<String, String> visitMBean(){
		Map<String, String> map = new HashMap<>();
		RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();
		String vendor1 = mxbean.getVmVendor();
//		System.out.println("vendor1:" + vendor1);
		map.put("vendor1:", vendor1);
		return map;		
	}
 
Example #20
Source Project: openjdk-8   Author: bpupadhyaya   File: ProcessTools.java    License: 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 #21
Source Project: LagMonitor   Author: games647   File: SystemCommand.java    License: MIT License 5 votes vote down vote up
private void displayRuntimeInfo(CommandSender sender, RuntimeMXBean runtimeBean) {
    long uptime = runtimeBean.getUptime();
    String uptimeFormat = LagMonitor.formatDuration(Duration.ofMillis(uptime));

    displayMemoryInfo(sender, Runtime.getRuntime());

    // runtime specific
    sendMessage(sender, "Uptime", uptimeFormat);
    sendMessage(sender, "Arguments", runtimeBean.getInputArguments().toString());
    sendMessage(sender, "Classpath", runtimeBean.getClassPath());
    sendMessage(sender, "Library path", runtimeBean.getLibraryPath());
}
 
Example #22
Source Project: sofa-jraft   Author: sofastack   File: UniqueIdUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets current pid, max pid 32 bit systems 32768, for 64 bit 4194304
 * http://unix.stackexchange.com/questions/16883/what-is-the-maximum-value-of-the-pid-of-a-process
 * http://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id
 */
private static int getProcessId() {
    String value = "";
    try {
        final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        value = runtime.getName();
    } catch (final Throwable t) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not invoke ManagementFactory.getRuntimeMXBean().getName(), {}.",
                StackTraceUtil.stackTrace(t));
        }
    }

    // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
    final int atIndex = value.indexOf('@');
    if (atIndex >= 0) {
        value = value.substring(0, atIndex);
    }

    int pid = -1;
    try {
        pid = Integer.parseInt(value);
    } catch (final NumberFormatException ignored) {
        // value did not contain an integer
    }

    if (pid < 0 || pid > MAX_PROCESS_ID) {
        pid = ThreadLocalRandom.current().nextInt(MAX_PROCESS_ID + 1);

        logger.warn("Failed to find the current process ID from '{}'; using a random value: {}.", value, pid);
    }

    return pid;
}
 
Example #23
Source Project: visualvm   Author: oracle   File: MonitoredDataImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
MonitoredDataImpl(JmxSupport jmxSupport,JvmMXBeans jmxModel) {
  this(jmxSupport);
  RuntimeMXBean runtimeBean = jmxModel.getRuntimeMXBean();
  upTime = runtimeBean.getUptime();
  ClassLoadingMXBean classBean = jmxModel.getClassLoadingMXBean();
  ThreadMXBean threadBean = jmxModel.getThreadMXBean();
  MemoryUsage mem = jmxModel.getMemoryMXBean().getHeapMemoryUsage();
  MemoryPoolMXBean permBean = jmxSupport.getPermGenPool();
  unloadedClasses = classBean.getUnloadedClassCount();
  loadedClasses = classBean.getLoadedClassCount() + unloadedClasses;
  sharedLoadedClasses = 0;
  sharedUnloadedClasses = 0;
  threadsDaemon = threadBean.getDaemonThreadCount();
  threadsLive = threadBean.getThreadCount();
  threadsLivePeak = threadBean.getPeakThreadCount();
  threadsStarted = threadBean.getTotalStartedThreadCount();
  applicationTime = 0;
  genCapacity = new long[2];
  genUsed = new long[2];
  genMaxCapacity = new long[2];
  genCapacity[0] = mem.getCommitted();
  genUsed[0] = mem.getUsed();
  genMaxCapacity[0] = mem.getMax();
  if (permBean != null) {
      MemoryUsage perm = permBean.getUsage();
      genCapacity[1] = perm.getCommitted();
      genUsed[1] = perm.getUsed();
      genMaxCapacity[1] = perm.getMax();
  }
}
 
Example #24
Source Project: pmq   Author: ppdaicorp   File: PropUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Integer getProcessId() {
	if (processId == null) {
		synchronized (PropUtil.class) {
			if (processId == null) {
				RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
				String name = runtime.getName();
				processId = Integer.parseInt(name.substring(0, name.indexOf("@")));
			}
		}
	}
	return processId;
}
 
Example #25
Source Project: quark   Author: qubole   File: Main.java    License: Apache License 2.0 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 #26
Source Project: pentaho-kettle   Author: pentaho   File: ServerStatus.java    License: Apache License 2.0 5 votes vote down vote up
public ServerStatus() {
  OperatingSystemMXBean operatingSystemMXBean =
    java.lang.management.ManagementFactory.getOperatingSystemMXBean();
  ThreadMXBean threadMXBean = java.lang.management.ManagementFactory.getThreadMXBean();
  RuntimeMXBean runtimeMXBean = java.lang.management.ManagementFactory.getRuntimeMXBean();

  int cores = Runtime.getRuntime().availableProcessors();

  long freeMemory = Runtime.getRuntime().freeMemory();
  long totalMemory = Runtime.getRuntime().totalMemory();
  String osArch = operatingSystemMXBean.getArch();
  String osName = operatingSystemMXBean.getName();
  String osVersion = operatingSystemMXBean.getVersion();
  double loadAvg = operatingSystemMXBean.getSystemLoadAverage();

  int threadCount = threadMXBean.getThreadCount();
  long allThreadsCpuTime = 0L;

  long[] threadIds = threadMXBean.getAllThreadIds();
  for ( int i = 0; i < threadIds.length; i++ ) {
    allThreadsCpuTime += threadMXBean.getThreadCpuTime( threadIds[i] );
  }

  long uptime = runtimeMXBean.getUptime();

  setCpuCores( cores );
  setCpuProcessTime( allThreadsCpuTime );
  setUptime( uptime );
  setThreadCount( threadCount );
  setLoadAvg( loadAvg );
  setOsName( osName );
  setOsVersion( osVersion );
  setOsArchitecture( osArch );
  setMemoryFree( freeMemory );
  setMemoryTotal( totalMemory );
}
 
Example #27
Source Project: flink   Author: flink-tpc-ds   File: EnvironmentInformation.java    License: Apache License 2.0 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 #28
Source Project: SWET   Author: sergueik   File: Log4j2Test.java    License: MIT License 5 votes vote down vote up
@Test
public void sampleLog4Jtest() {

	// Prints the jvm arguments. Must have "-DAPP_LOG_ROOT=c:/temp" --> location
	// of the logs.-
	RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
	List<String> jvmArgs = runtimeMXBean.getInputArguments();
	System.out.println("jvm arguments: " + jvmArgs);

	LOGGER.debug("Debug debugging message");
	LOGGER.info("Info information message");
	LOGGER.error("Error Message Logged !!!", new Exception("excepition"));

}
 
Example #29
Source Project: flink   Author: flink-tpc-ds   File: EnvironmentInformation.java    License: Apache License 2.0 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 #30
Source Project: 30-seconds-of-java   Author: shekhargulati   File: Snippets.java    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
public static boolean isDebuggerAttached() {
    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    return runtimeMXBean.getInputArguments()
            .stream()
            .anyMatch(arg -> arg.contains("-agentlib:jdwp"));

}