java.lang.management.ManagementFactory Java Examples
The following examples show how to use
java.lang.management.ManagementFactory.
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: Events.java From TencentKona-8 with GNU General Public License v2.0 | 7 votes |
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
Source File: TestLogConfigurationDeadLockWithConf.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@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 #3
Source File: SpringRejectedDeploymentTest.java From wildfly-camel with Apache License 2.0 | 6 votes |
@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 #4
Source File: ThroughputQueueSingleThreadTest.java From streams with Apache License 2.0 | 6 votes |
/** * 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 #5
Source File: DittoService.java From ditto with Eclipse Public License 2.0 | 6 votes |
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 #6
Source File: VmCommand.java From LagMonitor with MIT License | 6 votes |
@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 #7
Source File: PlatformLoggingMXBeanTest.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
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 #8
Source File: JMXResource.java From karyon with Apache License 2.0 | 6 votes |
/** * 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 #9
Source File: TestRaftLogMetrics.java From incubator-ratis with Apache License 2.0 | 6 votes |
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 File: BasicExecutor.java From sofa-tracer with Apache License 2.0 | 6 votes |
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 #11
Source File: ServerInfo.java From activemq-artemis with Apache License 2.0 | 6 votes |
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 #12
Source File: ScanManagerTest.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * 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 #13
Source File: Envs.java From dubbox with Apache License 2.0 | 6 votes |
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 #14
Source File: Performance.java From XRTB with Apache License 2.0 | 5 votes |
/** * Get CPU performance as a String, adjusted by cores * * @return String. Returns a cpu percentage string */ public static String getCpuPerfAsString() { OperatingSystemMXBean mx = java.lang.management.ManagementFactory.getOperatingSystemMXBean(); int cores = Runtime.getRuntime().availableProcessors(); double d = mx.getSystemLoadAverage() * 100 / cores; return formatter.format(d); }
Example #15
Source File: GetVMOption.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { List<HotSpotDiagnosticMXBean> list = ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class); HotSpotDiagnosticMXBean mbean = list.get(0); checkVMOption(mbean); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); mbean = ManagementFactory.newPlatformMXBeanProxy(mbs, HOTSPOT_DIAGNOSTIC_MXBEAN_NAME, HotSpotDiagnosticMXBean.class); checkVMOption(mbean); }
Example #16
Source File: TestThreadDumpMonitorContention.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
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 #17
Source File: MBeanServerMXBeanUnsupportedTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
public static void main(String args[]) throws Exception { System.setProperty("javax.management.builder.initial", MBeanServerBuilderImpl.class.getName()); try { ManagementFactory.getPlatformMBeanServer(); } catch (RuntimeException e) { System.out.println(">>> Unhappy Bye, Bye!"); throw e; } System.out.println(">>> Happy Bye, Bye!"); }
Example #18
Source File: LockDetectionIT.java From jreactive-8583 with Apache License 2.0 | 5 votes |
@BeforeAll public static void beforeAll() { threadMXBean = ManagementFactory.getThreadMXBean(); assertThat(threadMXBean.isThreadContentionMonitoringSupported()); threadMXBean.setThreadContentionMonitoringEnabled(true); monitoringThread = new Thread(() -> { while (latch.getCount() > 0) { detectThreadLocks(); } }); }
Example #19
Source File: JMXEndpointService.java From hawkular-agent with Apache License 2.0 | 5 votes |
private MBeanServerConnection getMBeanServerConnection() { // Find out what the name of the MBeanServer is from our custom data in the endpoint config. String mbsName = null; Map<String, ? extends Object> customData = getMonitoredEndpoint().getEndpointConfiguration().getCustomData(); if (customData != null) { Object nameObj = customData.get(MBEAN_SERVER_NAME_KEY); if (nameObj != null && !nameObj.toString().isEmpty()) { mbsName = nameObj.toString(); } } // Find the MBeanServer from its "name" where the "name" is nothing more than its default domain. // If name is null, we will use the platform MBeanServer. MBeanServer mbs = null; if (mbsName != null) { ArrayList<MBeanServer> allMbs = MBeanServerFactory.findMBeanServer(null); for (MBeanServer curMbs : allMbs) { if ((curMbs != null) && mbsName.equals(curMbs.getDefaultDomain())) { mbs = curMbs; break; } } } if (mbs == null) { mbs = ManagementFactory.getPlatformMBeanServer(); } return mbs; }
Example #20
Source File: GcProfiler.java From cache2k-benchmark with Apache License 2.0 | 5 votes |
@Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { installHooks(); long gcTime = 0; long gcCount = 0; for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { gcCount += bean.getCollectionCount(); gcTime += bean.getCollectionTime(); } this.beforeGCCount = gcCount; this.beforeGCTime = gcTime; this.beforeAllocated = HotspotAllocationSnapshot.create(); this.beforeTime = System.nanoTime(); }
Example #21
Source File: Pool.java From mariadb-connector-j with GNU Lesser General Public License v2.1 | 5 votes |
private void registerJmx() throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); String jmxName = poolTag.replace(":", "_"); ObjectName name = new ObjectName("org.mariadb.jdbc.pool:type=" + jmxName); if (!mbs.isRegistered(name)) { mbs.registerMBean(this, name); } }
Example #22
Source File: StreamsTaskCounterTest.java From streams with Apache License 2.0 | 5 votes |
/** * Remove registered mbeans from previous tests * @throws Exception */ @After public void unregisterMXBean() throws Exception { try { ManagementFactory.getPlatformMBeanServer().unregisterMBean(new ObjectName(String.format(StreamsTaskCounter.NAME_TEMPLATE, MBEAN_ID, STREAM_ID, STREAM_START_TIME))); } catch (InstanceNotFoundException ife) { //No-op } }
Example #23
Source File: ThreadMXBeanCpuTimeHandler.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
@Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { validator.validate(operation); try { long id = operation.require(PlatformMBeanConstants.ID).asLong(); context.getResult().set(ManagementFactory.getThreadMXBean().getThreadCpuTime(id)); } catch (UnsupportedOperationException e) { throw new OperationFailedException(e.toString()); } }
Example #24
Source File: ProcessInfo.java From Mycat-openEP with Apache License 2.0 | 5 votes |
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 #25
Source File: NetUtils.java From neural with MIT License | 5 votes |
public static String getProcessId() { if (PROCESS_ID != null) { return PROCESS_ID; } return PROCESS_ID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; }
Example #26
Source File: SysUtil.java From game-server with MIT License | 5 votes |
/** * 操作系统信息 * @author JiangZhiYong * @QQ 359135103 * 2017年10月12日 下午5:21:19 * @param spliteStr * @return */ public static String osInfo(String spliteStr) { OperatingSystemMXBean bean=ManagementFactory.getOperatingSystemMXBean(); StringBuilder sb = new StringBuilder(); sb.append("操作系统架构: ").append(bean.getArch()).append(spliteStr); sb.append("可使用的cpu数量: ").append(bean.getAvailableProcessors()).append(spliteStr); sb.append("操作系统名称: ").append(bean.getName()).append(spliteStr); sb.append("1分钟cpu消耗平均值: ").append(bean. getSystemLoadAverage()).append(spliteStr); sb.append("操作系统版本: ").append(bean.getVersion()).append(spliteStr); return sb.toString(); }
Example #27
Source File: CustomPropertiesTest.java From deltaspike with Apache License 2.0 | 5 votes |
@Test public void checkMBean() throws Exception { assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered( new ObjectName("cat:type=and,foo=bar,dummy=empty"))); assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered( new ObjectName("cat:type=and,name=nom,foo=bar,dummy=empty"))); }
Example #28
Source File: MetricsConfiguration.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 5 votes |
@PostConstruct public void init() { log.debug("Registering JVM gauges"); metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet()); metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge()); metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer())); metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet()); if (hikariDataSource != null) { log.debug("Monitoring the datasource"); // remove the factory created by HikariDataSourceMetricsPostProcessor until JHipster migrate to Micrometer hikariDataSource.setMetricsTrackerFactory(null); hikariDataSource.setMetricRegistry(metricRegistry); } if (jHipsterProperties.getMetrics().getJmx().isEnabled()) { log.debug("Initializing Metrics JMX reporting"); JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build(); jmxReporter.start(); } if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { log.info("Initializing Metrics Log reporting"); Marker metricsMarker = MarkerFactory.getMarker("metrics"); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LoggerFactory.getLogger("metrics")) .markWith(metricsMarker) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(); reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS); } }
Example #29
Source File: QuartzScheduler.java From AsuraFramework with Apache License 2.0 | 5 votes |
/** * 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 #30
Source File: BootstrapTest.java From JobX with Apache License 2.0 | 5 votes |
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; }