Java Code Examples for java.lang.management.ManagementFactory

The following examples show how to use java.lang.management.ManagementFactory. These examples are extracted from open source projects. 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: TencentKona-8   Source File: Events.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static String getProcessId(final String fallback) {
    // Note: may fail in some JVM implementations
    // therefore fallback has to be provided

    // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
   final String jvmName = ManagementFactory.getRuntimeMXBean().getName();

   final int index = jvmName.indexOf('@');

    if (index < 1) {
        // part before '@' empty (index = 0) / '@' not found (index = -1)
        return fallback;
    }

    try {
        return Long.toString(Long.parseLong(jvmName.substring(0, index)));
    } catch (NumberFormatException e) {
        // ignore
    }
    return fallback;
}
 
Example 2
@Test
public void testDeploymentRejectedForContextStartupFailure() throws Exception {

    List<String> names = contextRegistry.getCamelContextNames();
    Assert.assertEquals(Collections.emptyList(), names);

    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> onames = server.queryNames(new ObjectName("org.apache.camel:*"), null);
    Assert.assertEquals(Collections.emptySet(), onames);

    try {
        deployer.deploy(SIMPLE_JAR);
        Assert.fail("Expected deployment exception to be thrown but it was not");
    } catch (Exception e) {
        // Make sure the deployment was rolled back
        ServiceController<?> service = serviceContainer.getService(ServiceName.of("jboss.deployment.unit.\"simple.jar\""));
        Assert.assertNull("Expected simple.jar service to be null", service);
    } finally {
        deployer.undeploy(SIMPLE_JAR);
    }

    // @Ignore [CAMEL-13094] Context MBean not unregistered on startup failure
    //onames = server.queryNames(new ObjectName("org.apache.camel:*"), null);
    //Assert.assertEquals(Collections.emptySet(), onames);
}
 
Example 3
@Override
public void run() {
    while(goOn) {
        try {
            long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
            checkCount.incrementAndGet();
            ids = ids == null ? new long[0] : ids;
            if (ids.length > 0) {
                deadlocked.addAll(asList(ids));
            }
            if (ids.length == 1) {
                throw new RuntimeException("Found 1 deadlocked thread: "+ids[0]);
            } else if (ids.length > 0) {
                ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE);
                System.err.println("Found "+ids.length+" deadlocked threads: ");
                for (ThreadInfo inf : infos) {
                    System.err.println(inf.toString());
                }
                throw new RuntimeException("Found "+ids.length+" deadlocked threads");
            }
            Thread.sleep(100);
        } catch(InterruptedException | RuntimeException x) {
            fail(x);
        }
    }
}
 
Example 4
Source Project: LagMonitor   Source File: VmCommand.java    License: MIT License 6 votes vote down vote up
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!canExecute(sender, command)) {
        return true;
    }

    //java version info
    displayJavaVersion(sender);

    //java paths
    sendMessage(sender, "Java lib", System.getProperty("sun.boot.library.path", "Unknown"));
    sendMessage(sender, "Java home", System.getProperty("java.home", "Unknown"));
    sendMessage(sender, "Temp path", System.getProperty("java.io.tmpdir", "Unknown"));

    displayRuntimeInfo(sender, ManagementFactory.getRuntimeMXBean());
    displayCompilationInfo(sender, ManagementFactory.getCompilationMXBean());
    displayClassLoading(sender, ManagementFactory.getClassLoadingMXBean());

    //garbage collector
    for (GarbageCollectorMXBean collector : ManagementFactory.getGarbageCollectorMXBeans()) {
        displayCollectorStats(sender, collector);
    }

    return true;
}
 
Example 5
Source Project: sofa-tracer   Source File: BasicExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private String dumpThreadInfo() {
    final StringBuilder sb = new StringBuilder();

    final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    for (Thread t : threads) {
        ThreadInfo threadInfo = threadMXBean.getThreadInfo(t.getId());
        sb.append("{");
        sb.append("name=").append(t.getName()).append(",");
        sb.append("id=").append(t.getId()).append(",");
        sb.append("state=").append(threadInfo.getThreadState()).append(",");
        sb.append("lockInfo=").append(threadInfo.getLockInfo());
        sb.append("}");
    }

    return sb.toString();
}
 
Example 6
Source Project: activemq-artemis   Source File: ServerInfo.java    License: Apache License 2.0 6 votes vote down vote up
public String dump() {
   long maxMemory = Runtime.getRuntime().maxMemory();
   long totalMemory = Runtime.getRuntime().totalMemory();
   long freeMemory = Runtime.getRuntime().freeMemory();
   long availableMemory = freeMemory + maxMemory - totalMemory;
   double availableMemoryPercent = 100.0 * availableMemory / maxMemory;
   ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

   StringBuilder info = new StringBuilder("\n**** Server Dump ****\n");
   info.append(String.format("date:            %s%n", new Date()));
   info.append(String.format("free memory:      %s%n", SizeFormatterUtil.sizeof(freeMemory)));
   info.append(String.format("max memory:       %s%n", SizeFormatterUtil.sizeof(maxMemory)));
   info.append(String.format("total memory:     %s%n", SizeFormatterUtil.sizeof(totalMemory)));
   info.append(String.format("available memory: %.2f%%%n", availableMemoryPercent));
   info.append(appendPagingInfos());
   info.append(String.format("# of thread:     %d%n", threadMXBean.getThreadCount()));
   info.append(String.format("# of conns:      %d%n", server.getConnectionCount()));
   info.append("********************\n");
   return info.toString();
}
 
Example 7
Source Project: jdk8u-jdk   Source File: ScanManagerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test of preRegister method, of class com.sun.jmx.examples.scandir.ScanManager.
 */
public void testPreRegister() throws Exception {
    System.out.println("preRegister");

    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = new ObjectName("DownUnder:type=Wombat");
    ScanManager instance = new ScanManager();

    ObjectName expResult = ScanManager.SCAN_MANAGER_NAME;
    ObjectName result;
    try {
        result = instance.preRegister(server, name);
        throw new RuntimeException("bad name accepted!");
    } catch (IllegalArgumentException x) {
        // OK!
        result = instance.preRegister(server, null);
    }
    assertEquals(expResult, result);
    result = instance.preRegister(server, ScanManager.SCAN_MANAGER_NAME);
    assertEquals(expResult, result);
}
 
Example 8
Source Project: dubbox   Source File: Envs.java    License: Apache License 2.0 6 votes vote down vote up
public void index(Map<String, Object> context) throws Exception {
    Map<String, String> properties = new TreeMap<String, String>();
    StringBuilder msg = new StringBuilder();
    msg.append("Version: ");
    msg.append(Version.getVersion(Envs.class, "2.2.0"));
    properties.put("Registry", msg.toString());
    String address = NetUtils.getLocalHost();
    properties.put("Host", NetUtils.getHostName(address) + "/" + address);
    properties.put("Java", System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version"));
    properties.put("OS", System.getProperty("os.name") + " "
            + System.getProperty("os.version"));
    properties.put("CPU", System.getProperty("os.arch", "") + ", "
            + String.valueOf(Runtime.getRuntime().availableProcessors()) + " cores");
    properties.put("Locale", Locale.getDefault().toString() + "/"
            + System.getProperty("file.encoding"));
    properties.put("Uptime", formatUptime(ManagementFactory.getRuntimeMXBean().getUptime()) 
            + " From " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())) 
            + " To " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date()));
    context.put("properties", properties);
}
 
Example 9
Source Project: incubator-ratis   Source File: TestRaftLogMetrics.java    License: Apache License 2.0 6 votes vote down vote up
static void assertFlushCount(RaftServerImpl server) throws Exception {
  final String flushTimeMetric = RaftStorageTestUtils.getLogFlushTimeMetric(server.getMemberId().toString());
  RatisMetricRegistry ratisMetricRegistry = new RaftLogMetrics(server.getMemberId().toString()).getRegistry();
  Timer tm = (Timer) ratisMetricRegistry.get(RAFT_LOG_FLUSH_TIME);
  Assert.assertNotNull(tm);

  final MetricsStateMachine stateMachine = MetricsStateMachine.get(server);
  final int expectedFlush = stateMachine.getFlushCount();

  JavaUtils.attemptRepeatedly(() -> {
    Assert.assertEquals(expectedFlush, tm.getCount());
    return null;
  }, 50, HUNDRED_MILLIS, "expectedFlush == tm.getCount()", null);

  Assert.assertTrue(tm.getMeanRate() > 0);

  // Test jmx
  ObjectName oname = new ObjectName(RATIS_APPLICATION_NAME_METRICS, "name", flushTimeMetric);
  Assert.assertEquals(expectedFlush,
      ((Long) ManagementFactory.getPlatformMBeanServer().getAttribute(oname, "Count"))
          .intValue());
}
 
Example 10
Source Project: karyon   Source File: JMXResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate JSON for the MBean operations
 *
 * @param objName
 * @return
 * @throws Exception
 */
private JSONArray emitOperations(ObjectName objName) throws Exception {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objName);
    JSONArray ar = new JSONArray();

    MBeanOperationInfo[] operations = mBeanInfo.getOperations();
    for (MBeanOperationInfo operation : operations) {
        JSONObject obj = new JSONObject();
        obj.put("name", operation.getName());
        obj.put("description", operation.getDescription());
        obj.put("returnType", operation.getReturnType());
        obj.put("impact", operation.getImpact());

        JSONArray params = new JSONArray();
        for (MBeanParameterInfo param : operation.getSignature()) {
            JSONObject p = new JSONObject();
            p.put("name", param.getName());
            p.put("type", param.getType());
            params.put(p);
        }
        obj.put("params", params);
        ar.put(obj);
    }
    return ar;
}
 
Example 11
public static void main(String[] argv) throws Exception {
    PlatformLoggingMXBean mbean =
        ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);
    ObjectName objname = mbean.getObjectName();
    if (!objname.equals(new ObjectName(LogManager.LOGGING_MXBEAN_NAME))) {
        throw new RuntimeException("Invalid ObjectName " + objname);
    }

    // check if the PlatformLoggingMXBean is registered in the platform MBeanServer
    MBeanServer platformMBS = ManagementFactory.getPlatformMBeanServer();
    ObjectName objName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME);

    // We could call mbs.isRegistered(objName) here.
    // Calling getMBeanInfo will throw exception if not found.
    platformMBS.getMBeanInfo(objName);

    if (!platformMBS.isInstanceOf(objName, "java.lang.management.PlatformLoggingMXBean") ||
        !platformMBS.isInstanceOf(objName, "java.util.logging.LoggingMXBean")) {
        throw new RuntimeException(objName + " is of unexpected type");
    }

    // test if PlatformLoggingMXBean works properly in a MBeanServer
    PlatformLoggingMXBeanTest test = new PlatformLoggingMXBeanTest();
    test.runTest(mbean);
}
 
Example 12
Source Project: streams   Source File: ThroughputQueueSingleThreadTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test that mulitple mbeans of the same type with a different name can be registered
 */
@Test
public void testMultipleMBeanRegistrations() {
  try {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Integer beanCount = mbs.getMBeanCount();
    int numReg = randomIntBetween(2, 100);
    for(int i=0; i < numReg; ++i) {
      ThroughputQueue queue = new ThroughputQueue(MBEAN_ID + "" + i, STREAM_ID, STREAM_START_TIME);
      Assert.assertEquals("Expected bean to be registered", new Integer(beanCount + (i+1)), mbs.getMBeanCount());
      ObjectInstance mBean = mbs.getObjectInstance(new ObjectName(String.format(ThroughputQueue.NAME_TEMPLATE, MBEAN_ID + "" + i, STREAM_ID, STREAM_START_TIME)));
      Assert.assertNotNull(mBean);
    }
  } catch (Exception e) {
    Assert.fail("Assert.failed to register MXBean : "+e.getMessage());
  }
}
 
Example 13
Source Project: ditto   Source File: DittoService.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private Config appendDittoInfo(final Config config) {
    final String instanceId = InstanceIdentifierSupplier.getInstance().get();

    final ConfigValue service = ConfigFactory.empty()
            .withValue("name", ConfigValueFactory.fromAnyRef(serviceName))
            .withValue("instance-id", ConfigValueFactory.fromAnyRef(instanceId))
            .root();

    final ConfigValue vmArgs =
            ConfigValueFactory.fromIterable(ManagementFactory.getRuntimeMXBean().getInputArguments());

    final ConfigValue env = ConfigValueFactory.fromMap(System.getenv());

    return config.withValue("ditto.info",
            ConfigFactory.empty()
                    .withValue("service", service)
                    .withValue("vm-args", vmArgs)
                    .withValue("env", env)
                    .root());
}
 
Example 14
Source Project: dubbo3   Source File: LoadStatusChecker.java    License: Apache License 2.0 5 votes vote down vote up
public Status check() {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load;
	try {
	    Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class<?>[0]);
	    load = (Double)method.invoke(operatingSystemMXBean, new Object[0]);
	} catch (Throwable e) {
	    load = -1;
	}
	int cpu = operatingSystemMXBean.getAvailableProcessors();
    return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), "Load: " + load + " / CPU: " + cpu);
}
 
Example 15
Source Project: AsuraFramework   Source File: QuartzScheduler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unregister the scheduler from the local MBeanServer.
 */
private void unregisterJMX() throws Exception {
	String jmxObjectName = resources.getJMXObjectName();
	MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
	mbs.unregisterMBean(new ObjectName(jmxObjectName));
	jmxBean.setSampledStatisticsEnabled(false);
    getLog().info("Scheduler unregistered from name '" + jmxObjectName + "' in the local MBeanServer.");
}
 
Example 16
Source Project: h2o-2   Source File: OSUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Safe call to obtain size of total physical memory.
 *
 * <p>It is platform dependent and returns size of machine physical
 * memory in bytes</p>
 *
 * @return total size of machine physical memory in bytes or -1 if the attribute is not available.
 */
public static long getTotalPhysicalMemory() {
  long memory = -1;
  try {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    Object attribute = mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "TotalPhysicalMemorySize");
    return (Long) attribute;
  } catch (Throwable e) { e.printStackTrace(); }
  return memory;
}
 
Example 17
Source Project: wildfly-camel   Source File: JMXIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMonitorMBeanAttribute() throws Exception {
    CamelContext context = contextRegistry.getCamelContext("jmx-context-1");
    Assert.assertNotNull("jmx-context-1 not null", context);
    final String routeName = context.getRoutes().get(0).getId();

    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    ObjectName onameAll = ObjectNameFactory.create("org.apache.camel:*");
    Set<ObjectInstance> mbeans = server.queryMBeans(onameAll, null);
    System.out.println(">>>>>>>>> MBeans: " + mbeans.size());
    mbeans.forEach(mb -> System.out.println(mb.getObjectName()));

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("jmx:platform?format=raw&objectDomain=org.apache.camel&key.context=jmx-context-1&key.type=routes&key.name=\"" + routeName + "\"" +
            "&monitorType=counter&observedAttribute=ExchangesTotal&granularityPeriod=500").
            to("direct:end");
        }
    });

    camelctx.start();
    try {
        ConsumerTemplate consumer = camelctx.createConsumerTemplate();
        MonitorNotification notifcation = consumer.receiveBody("direct:end", MonitorNotification.class);
        Assert.assertEquals("ExchangesTotal", notifcation.getObservedAttribute());
    } finally {
        camelctx.close();
    }
}
 
Example 18
Source Project: HeavenMS   Source File: TimerManager.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private TimerManager() {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        mBeanServer.registerMBean(this, new ObjectName("server:type=TimerManger"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 19
Source Project: openjdk-jdk8u   Source File: JvmMemoryImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Getter for the "JvmMemoryPendingFinalCount" variable.
 */
public Long getJvmMemoryPendingFinalCount()
    throws SnmpStatusException {
    final long val = ManagementFactory.getMemoryMXBean().
        getObjectPendingFinalizationCount();

    if (val > -1) return new Long((int)val);

    // Should never happen... but stay safe all the same.
    //
    else return new Long(0);
}
 
Example 20
Source Project: Moss   Source File: GCLogEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<String> getGCLogPath(){
    // -Xlog:gc:./gclogs
    // -Xloggc:./gclogs
    return ManagementFactory.getRuntimeMXBean().getInputArguments()
            .stream()
            .filter(s-> s.startsWith("-Xlog"))
            .map(s-> s.replace("-Xlog:gc:","").replace("-Xloggc:",""))
            .filter(f->new File(f).exists())
            .findFirst();
}
 
Example 21
/**
 * Test of addNotificationListener method, of class com.sun.jmx.examples.scandir.DirectoryScanner.
 */
public void testAddNotificationListener() throws Exception {
    System.out.println("addNotificationListener");

    final ScanManagerMXBean manager = ScanManager.register();
    final Call op = new Call() {
        public void call() throws Exception {
            manager.start();
        }
        public void cancel() throws Exception {
            manager.stop();
        }
    };
    try {
        final String tmpdir = System.getProperty("java.io.tmpdir");
        final ScanDirConfigMXBean config = manager.getConfigurationMBean();
        final DirectoryScannerConfig bean =
                config.addDirectoryScanner("test1",tmpdir,".*",0,0);
        manager.applyConfiguration(true);
        final DirectoryScannerMXBean proxy =
                manager.getDirectoryScanners().get("test1");
       doTestOperation(proxy,op,
                        EnumSet.of(RUNNING,SCHEDULED),
                        "scan");
    } finally {
        try {
            ManagementFactory.getPlatformMBeanServer().
                    unregisterMBean(ScanManager.SCAN_MANAGER_NAME);
        } catch (Exception x) {
            System.err.println("Failed to cleanup: "+x);
        }
    }
}
 
Example 22
public static void main(String[] args) {
    SysOutUtils.sysout(ManagementFactory.getRuntimeMXBean().getName());
    UncaughtExceptionHandlerInitializer.initUncaughtExceptionHandler();

    Example_7a_Model model = new Example_7a_Model();
    Example_7a_ViewModel viewModel = new Example_7a_ViewModel();
    viewModel.connectTo(model);

    SwingUtilities2.invokeLater(() -> {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        Example_7a_View view = new Example_7a_View();
        view.bind(viewModel);
        view.setVisible(true);
    });
}
 
Example 23
Source Project: boon   Source File: Sys.java    License: Apache License 2.0 5 votes vote down vote up
public static long openFileDescriptorCount() {

        if (oracleJVMAndUnix) {

            UnixOperatingSystemMXBean unix = (UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
            return unix.getOpenFileDescriptorCount();
        }else {
            return -1;
        }
    }
 
Example 24
Source Project: Doradus   Source File: ThreadDumpCmd.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RESTResponse invoke() {
    StringBuilder dump = new StringBuilder();
    dump.append("Doradus Thread Dump @ ");
    dump.append(Utils.formatDate(System.currentTimeMillis()));
    dump.append("\n\n");
    
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadBean.dumpAllThreads(true, true);
    for (ThreadInfo thread : threadInfos) {
        dump.append(thread.toString());
    }
    return new RESTResponse(HttpCode.OK, dump.toString());
}
 
Example 25
public static double getLoad() {
	try {
		OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
		return os.getSystemLoadAverage();
	}
	catch (Exception ex) {
	}
	return 0;
}
 
Example 26
/**
 * Test of schedule method, of class com.sun.jmx.examples.scandir.ScanManager.
 */
public void testSchedule() throws Exception {
    System.out.println("schedule");

    final long delay = 10000L;
    final long interval = 10000L;

    final ScanManagerMXBean manager = ScanManager.register();
    final Call op = new Call() {
        public void call() throws Exception {
            manager.schedule(delay,interval);
            assertEquals(SCHEDULED,manager.getState());
        }
        public void cancel() throws Exception {
            manager.stop();
        }
    };
    try {
        doTestOperation(manager,op,EnumSet.of(SCHEDULED),
                "schedule");
    } finally {
        try {
            ManagementFactory.getPlatformMBeanServer().
                    unregisterMBean(ScanManager.SCAN_MANAGER_NAME);
        } catch (Exception x) {
            System.err.println("Failed to cleanup: "+x);
        }
    }
}
 
Example 27
public static void main(String[] args) throws Exception {
    CountDownLatch prepareLatch = new CountDownLatch(2);
    AtomicInteger goLatch = new AtomicInteger(1);
    Task taskA = new Task(prepareLatch, goLatch, AnnA.class);
    Task taskB = new Task(prepareLatch, goLatch, AnnB.class);
    taskA.start();
    taskB.start();
    // wait until both threads start-up
    prepareLatch.await();
    // let them go
    goLatch.set(0);
    // obtain ThreadMXBean
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    // wait for threads to finish or dead-lock
    while (taskA.isAlive() || taskB.isAlive()) {
        // attempt to join threads
        taskA.join(500L);
        taskB.join(500L);
        // detect dead-lock
        long[] deadlockedIds = threadBean.findMonitorDeadlockedThreads();
        if (deadlockedIds != null && deadlockedIds.length > 0) {
            StringBuilder sb = new StringBuilder("deadlock detected:\n\n");
            for (ThreadInfo ti : threadBean.getThreadInfo(deadlockedIds, Integer.MAX_VALUE)) {
                sb.append(ti);
            }
            throw new IllegalStateException(sb.toString());
        }
    }
}
 
Example 28
Source Project: ClusterDeviceControlPlatform   Source File: Test.java    License: MIT License 5 votes vote down vote up
private static void printOperatingSystemInfo() {
    OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
    //相当于System.getProperty("os.name").
    System.out.println("系统名称:" + system.getName());
    //相当于System.getProperty("os.version").
    System.out.println("系统版本:" + system.getVersion());
    //相当于System.getProperty("os.arch").
    System.out.println("操作系统的架构:" + system.getArch());
    //相当于 Runtime.availableProcessors()
    System.out.println("可用的内核数:" + system.getAvailableProcessors());

    if (isSunOsMBean(system)) {
        long totalPhysicalMemory = getLongFromOperatingSystem(system, "getTotalPhysicalMemorySize");
        long freePhysicalMemory = getLongFromOperatingSystem(system, "getFreePhysicalMemorySize");
        long usedPhysicalMemorySize = totalPhysicalMemory - freePhysicalMemory;

        System.out.println("总物理内存(M):" + totalPhysicalMemory / MB);
        System.out.println("已用物理内存(M):" + usedPhysicalMemorySize / MB);
        System.out.println("剩余物理内存(M):" + freePhysicalMemory / MB);

        long totalSwapSpaceSize = getLongFromOperatingSystem(system, "getTotalSwapSpaceSize");
        long freeSwapSpaceSize = getLongFromOperatingSystem(system, "getFreeSwapSpaceSize");
        long usedSwapSpaceSize = totalSwapSpaceSize - freeSwapSpaceSize;

        System.out.println("总交换空间(M):" + totalSwapSpaceSize / MB);
        System.out.println("已用交换空间(M):" + usedSwapSpaceSize / MB);
        System.out.println("剩余交换空间(M):" + freeSwapSpaceSize / MB);
    }
}
 
Example 29
Source Project: flink   Source File: MetricUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static void instantiateGarbageCollectorMetrics(MetricGroup metrics) {
	List<GarbageCollectorMXBean> garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans();

	for (final GarbageCollectorMXBean garbageCollector: garbageCollectors) {
		MetricGroup gcGroup = metrics.addGroup(garbageCollector.getName());

		gcGroup.<Long, Gauge<Long>>gauge("Count", garbageCollector::getCollectionCount);
		gcGroup.<Long, Gauge<Long>>gauge("Time", garbageCollector::getCollectionTime);
	}
}
 
Example 30
Source Project: hadoop-ozone   Source File: TestSCMMXBean.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void init() throws IOException, TimeoutException,
    InterruptedException {
  conf = new OzoneConfiguration();
  cluster = MiniOzoneCluster.newBuilder(conf)
      .setNumDatanodes(numOfDatanodes)
      .build();
  cluster.waitForClusterToBeReady();
  scm = cluster.getStorageContainerManager();
  mbs = ManagementFactory.getPlatformMBeanServer();
}