Java Code Examples for java.lang.management.ManagementFactory

The following are top voted examples for showing how to use java.lang.management.ManagementFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: keyboard-light-composer   File: CpuUsage.java   View source code 7 votes vote down vote up
public static double getProcessCpuLoad() throws Exception {

		MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
		ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
		AttributeList list = mbs.getAttributes(name, new String[] { "SystemCpuLoad" });

		if (list.isEmpty())
			return Double.NaN;

		Attribute att = (Attribute) list.get(0);
		Double value = (Double) att.getValue();

		// usually takes a couple of seconds before we get real values
		if (value == -1.0)
			return Double.NaN;
		// returns a percentage value with 1 decimal point precision
		return value;
	}
 
Example 2
Project: ditb   File: TimedOutTestsListener.java   View source code 6 votes vote down vote up
static String buildDeadlockInfo() {
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  long[] threadIds = threadBean.findMonitorDeadlockedThreads();
  if (threadIds != null && threadIds.length > 0) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter out = new PrintWriter(stringWriter);
    
    ThreadInfo[] infos = threadBean.getThreadInfo(threadIds, true, true);
    for (ThreadInfo ti : infos) {
      printThreadInfo(ti, out);
      printLockInfo(ti.getLockedSynchronizers(), out);
      out.println();
    }
    
    out.close();
    return stringWriter.toString();
  } else {
    return null;
  }
}
 
Example 3
Project: openjdk-jdk10   File: RMIConnectorLogAttributesTest.java   View source code 6 votes vote down vote up
private JMXConnectorServer startServer(int rmiPort) throws Exception {
    System.out.println("DEBUG: Create RMI registry on port " + rmiPort);
    LocateRegistry.createRegistry(rmiPort);

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    HashMap<String,Object> env = new HashMap<String,Object>();

    JMXServiceURL url =
            new JMXServiceURL("service:jmx:rmi:///jndi/rmi://127.0.0.1:" + rmiPort + "/jmxrmi");
    JMXConnectorServer cs =
            JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);

    cs.start();
    System.out.println("DEBUG: Started the RMI connector server");
    return cs;
}
 
Example 4
Project: apache-tomcat-7.0.73-with-comment   File: JmxPasswordTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.datasource.setDriverClassName(Driver.class.getName());
    this.datasource.setUrl("jdbc:tomcat:test");
    this.datasource.setPassword(password);
    this.datasource.setUsername(username);
    this.datasource.getConnection().close();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    String domain = "tomcat.jdbc";
    Hashtable<String,String> properties = new Hashtable<String,String>();
    properties.put("type", "ConnectionPool");
    properties.put("class", this.getClass().getName());
    oname = new ObjectName(domain,properties);
    ConnectionPool pool = datasource.createPool();
    org.apache.tomcat.jdbc.pool.jmx.ConnectionPool jmxPool = new org.apache.tomcat.jdbc.pool.jmx.ConnectionPool(pool);
    mbs.registerMBean(jmxPool, oname);

}
 
Example 5
Project: ats-framework   File: ThreadUtils.java   View source code 6 votes vote down vote up
/**
 * @return a list of all threads started in the JVM.
 */
public List<Thread> getAllThreads() {

    final ThreadGroup root = getRootThreadGroup();
    final ThreadMXBean thbean = ManagementFactory.getThreadMXBean();
    // get the number of all live threads
    int nAlloc = thbean.getThreadCount();
    int n = 0;
    Thread[] threads;

    do {
        nAlloc *= 2; // increase the size since more threads may have been created
        threads = new Thread[nAlloc];
        n = root.enumerate(threads, true); // get all active threads from this thread group
    } while (n == nAlloc); // stop if all active threads are enumerated

    List<Thread> res = new ArrayList<Thread>();
    for (Thread th : threads) {
        res.add(th);
    }

    return res;
}
 
Example 6
Project: GitHub   File: BenchmarkMain_EishayEncode_WriteAsArray.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    SerializeConfig config = SerializeConfig.getGlobalInstance();
    config.put(MediaContent.class, new MediaContentSerializer());
    config.put(Media.class, new MediaSerializer());
    config.put(Image.class, new ImageSerializer());
    
    System.out.println(System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version"));
    List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
    System.out.println(arguments);

    MediaContent content = EishayDecodeBytes.instance.getContent();
    String text = encode(content);
    System.out.println(text);
    
    for (int i = 0; i < 10; ++i) {
        perf(text);
    }
}
 
Example 7
Project: CloudNet   File: CommandResource.java   View source code 6 votes vote down vote up
@Override
public boolean execute(CommandSender sender, String s, String[] strings)
{
    if(!testPermission(sender)) return false;
    long used = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1048576L;
    long max = Runtime.getRuntime().maxMemory() / 1048576L;

    sender.sendMessage(CloudAPI.getInstance().getPrefix() + " ");
    sender.sendMessage(CloudAPI.getInstance().getPrefix() + "§7Server: §b" + CloudAPI.getInstance().getServerId() + ":" + CloudAPI.getInstance().getUniqueId());
    sender.sendMessage(CloudAPI.getInstance().getPrefix() + "§7State§8: §b" + CloudServer.getInstance().getServerState());
    sender.sendMessage(CloudAPI.getInstance().getPrefix() + "§7Template: §b" + CloudServer.getInstance().getTemplate().getName());
    sender.sendMessage(CloudAPI.getInstance().getPrefix() + "§7Memory: §b" + used + "§7/§b" + max + "MB");
    sender.sendMessage(CloudAPI.getInstance().getPrefix() + "§7CPU-Usage internal: §b" + NetworkUtils.internalCpuUsage());
    sender.sendMessage(CloudAPI.getInstance().getPrefix() + " ");
    return false;
}
 
Example 8
Project: ChronoBike   File: CodeManager.java   View source code 6 votes vote down vote up
public static void initCodeSizeLimits(int nMaxSizeMemPoolCodeCache, int nMaxSizeMemPoolPermGen)
{
	// PJD remove ibm JMV
	List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
	for (MemoryPoolMXBean p: pools)
	{
		if(p.getType().compareTo(MemoryType.NON_HEAP) == 0)
		{
			String cs = p.getName();
			if(cs.equalsIgnoreCase("Code Cache"))
				p.setUsageThreshold((long)nMaxSizeMemPoolCodeCache * 1024L * 1024L);
			else if(cs.equalsIgnoreCase("Perm Gen"))
				p.setUsageThreshold((long)nMaxSizeMemPoolPermGen * 1024L * 1024L);
		}
	}
}
 
Example 9
Project: hadoop   File: MBeanUtil.java   View source code 6 votes vote down vote up
/**
 * Register the MBean using our standard MBeanName format
 * "hadoop:service=<serviceName>,name=<nameName>"
 * Where the <serviceName> and <nameName> are the supplied parameters
 *    
 * @param serviceName
 * @param nameName
 * @param theMbean - the MBean to register
 * @return the named used to register the MBean
 */	
static public ObjectName registerMBean(final String serviceName, 
  							final String nameName,
  							final Object theMbean) {
  final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  ObjectName name = getMBeanName(serviceName, nameName);
  try {
    mbs.registerMBean(theMbean, name);
    return name;
  } catch (InstanceAlreadyExistsException ie) {
    // Ignore if instance already exists 
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}
 
Example 10
Project: DecompiledMinecraft   File: PlayerUsageSnooper.java   View source code 6 votes vote down vote up
private void addJvmArgsToSnooper()
{
    RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean();
    List<String> list = runtimemxbean.getInputArguments();
    int i = 0;

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

    this.addClientStat("jvm_args", Integer.valueOf(i));
}
 
Example 11
Project: ditb   File: Utils.java   View source code 6 votes vote down vote up
/**
 * Returns a map of garbage collectors and their stats.
 * The first object in the array is the total count since JVM start and the
 * second is the total time (ms) since JVM start.
 * If a garbage collectors does not support the collector MXBean, then it
 * will not be represented in the map.
 * @return A non-null map of garbage collectors and their metrics. The map
 * may be empty.
 */
public static Map<String, Long[]> getGCStatst() {
  final List<GarbageCollectorMXBean> gcBeans =
      ManagementFactory.getGarbageCollectorMXBeans();
  final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size());
  for (final GarbageCollectorMXBean bean : gcBeans) {
    if (!bean.isValid() || bean.getCollectionCount() < 0 ||
        bean.getCollectionTime() < 0) {
      continue;
    }

    final Long[] measurements = new Long[]{
        bean.getCollectionCount(),
        bean.getCollectionTime()
    };
    map.put(bean.getName().replace(" ", "_"), measurements);
  }
  return map;
}
 
Example 12
Project: openjdk-jdk10   File: ConcurrentAssociateTest.java   View source code 6 votes vote down vote up
/**
 * A debugging tool to print stack traces of most threads, as jstack does.
 * Uninteresting threads are filtered out.
 */
static void dumpTestThreads() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    System.err.println("------ stacktrace dump start ------");
    for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
        String name = info.getThreadName();
        if ("Signal Dispatcher".equals(name))
            continue;
        if ("Reference Handler".equals(name)
            && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
            continue;
        if ("Finalizer".equals(name)
            && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
            continue;
        System.err.print(info);
    }
    System.err.println("------ stacktrace dump end ------");
}
 
Example 13
Project: Backmemed   File: Snooper.java   View source code 6 votes vote down vote up
private void addJvmArgsToSnooper()
{
    RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean();
    List<String> list = runtimemxbean.getInputArguments();
    int i = 0;

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

    this.addClientStat("jvm_args", Integer.valueOf(i));
}
 
Example 14
Project: mycat-src-1.6.1-RELEASE   File: EnvironmentInformation.java   View source code 6 votes vote down vote up
/**
 * The maximum JVM heap size, in bytes.
 * 
 * @return The maximum JVM heap size, in bytes.
 */
public static long getMaxJvmHeapMemory() {
	long maxMemory = Runtime.getRuntime().maxMemory();

	if (maxMemory == Long.MAX_VALUE) {
		// amount of free memory unknown
		try {
			// workaround for Oracle JDK
			OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
			Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean");
			Method method = clazz.getMethod("getTotalPhysicalMemorySize");
			maxMemory = (Long) method.invoke(operatingSystemMXBean) / 4;
		}
		catch (Throwable e) {
			throw new RuntimeException("Could not determine the amount of free memory.\n" +
					"Please set the maximum memory for the JVM, e.g. -Xmx512M for 512 megabytes.");
		}
	}
	
	return maxMemory;
}
 
Example 15
Project: QDrill   File: ThreadsIterator.java   View source code 6 votes vote down vote up
@Override
public Object next() {
  if (!beforeFirst) {
    throw new IllegalStateException();
  }
  beforeFirst = false;
  final ThreadsInfo threadsInfo = new ThreadsInfo();

  final DrillbitEndpoint endpoint = context.getIdentity();
  threadsInfo.hostname = endpoint.getAddress();
  threadsInfo.user_port = endpoint.getUserPort();

  final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  threadsInfo.total_threads = threadMXBean.getPeakThreadCount();
  threadsInfo.busy_threads = threadMXBean.getThreadCount();
  return threadsInfo;
}
 
Example 16
Project: openjdk-jdk10   File: JstatGcCapacityResults.java   View source code 6 votes vote down vote up
/**
 * Check if the tenured generation are currently using a parallel GC.
 */
protected static boolean isTenuredParallelGC() {
    // Currently the only parallel GC for the tenured generation is PS MarkSweep.
    List<String> parallelGCs = Arrays.asList(new String[] { "PS MarkSweep"});
    try {
        List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean bean : beans) {
            if (parallelGCs.contains(bean.getName())) {
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 17
Project: lazycat   File: Registry.java   View source code 6 votes vote down vote up
/**
 * Factory method to create (if necessary) and return our
 * <code>MBeanServer</code> instance.
 *
 */
public synchronized MBeanServer getMBeanServer() {
	long t1 = System.currentTimeMillis();

	if (server == null) {
		if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
			server = MBeanServerFactory.findMBeanServer(null).get(0);
			if (log.isDebugEnabled()) {
				log.debug("Using existing MBeanServer " + (System.currentTimeMillis() - t1));
			}
		} else {
			server = ManagementFactory.getPlatformMBeanServer();
			if (log.isDebugEnabled()) {
				log.debug("Creating MBeanServer" + (System.currentTimeMillis() - t1));
			}
		}
	}
	return (server);
}
 
Example 18
Project: aws-sdk-java-v2   File: Memory.java   View source code 6 votes vote down vote up
/**
 * Returns a summary information about the memory pools.
 */
public static String poolSummaries() {
    // Why ? list-archive?4273859
    // How ? http://stackoverflow.com/questions/697336/how-do-i-programmatically-find-out-my-permgen-space-usage
    //       http://stackoverflow.com/questions/8356416/xxmaxpermsize-with-or-without-xxpermsize
    StringBuilder sb = new StringBuilder();
    Iterator<MemoryPoolMXBean> iter =
            ManagementFactory.getMemoryPoolMXBeans().iterator();
    while (iter.hasNext()) {
        MemoryPoolMXBean item = iter.next();
        String name = item.getName();
        MemoryType type = item.getType();
        MemoryUsage usage = item.getUsage();
        MemoryUsage peak = item.getPeakUsage();
        MemoryUsage collections = item.getCollectionUsage();
        sb.append(String.format("Memory pool name: " + name
                                + ", type: " + type
                                + ", usage: " + usage
                                + ", peak: " + peak
                                + ", collections: " + collections
                                + "\n"));
    }
    return sb.toString();
}
 
Example 19
Project: openjdk-jdk10   File: Suicide.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    String cmd = null;
    try {
        String pidStr = ManagementFactory.getRuntimeMXBean().getName()
                .split("@")[0];
        String osName = System.getProperty("os.name");
        if (osName.contains("Windows")) {
            cmd = "taskkill.exe /F /PID " + pidStr;
        } else {
            cmd = "kill -9 " + pidStr;
        }

        System.out.printf("executing `%s'%n", cmd);
        Runtime.getRuntime().exec(cmd);
        Thread.sleep(2000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.err.printf("TEST/ENV BUG: %s didn't kill JVM%n", cmd);
    System.exit(1);
}
 
Example 20
Project: monarch   File: LauncherMemberMXBeanIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void testQueryForMemberMXBean() throws Exception {
  final Properties props = new Properties();
  props.setProperty(MCAST_PORT, "0");
  props.setProperty(LOCATORS, "");
  props.setProperty("name", getUniqueName());
  new CacheFactory(props).create();

  final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
  final ObjectName pattern = ObjectName.getInstance("GemFire:type=Member,*");

  waitForMemberMXBean(mbeanServer, pattern);

  final Set<ObjectName> mbeanNames = mbeanServer.queryNames(pattern, null);
  assertFalse(mbeanNames.isEmpty());
  assertEquals("mbeanNames=" + mbeanNames, 1, mbeanNames.size());

  final ObjectName objectName = mbeanNames.iterator().next();
  final MemberMXBean mbean = MBeanServerInvocationHandler.newProxyInstance(mbeanServer,
      objectName, MemberMXBean.class, false);

  assertNotNull(mbean);
  assertEquals(ProcessUtils.identifyPid(), mbean.getProcessId());
  assertEquals(getUniqueName(), mbean.getName());
  assertEquals(getUniqueName(), mbean.getMember());
}
 
Example 21
Project: ditb   File: HeapMemorySizeUtil.java   View source code 5 votes vote down vote up
/**
 * @param conf
 * @return The on heap size for L2 block cache.
 */
public static float getL2BlockCacheHeapPercent(Configuration conf) {
  float l2CachePercent = 0.0F;
  String bucketCacheIOEngineName = conf.get(HConstants.BUCKET_CACHE_IOENGINE_KEY, null);
  // L2 block cache can be on heap when IOEngine is "heap"
  if (bucketCacheIOEngineName != null && bucketCacheIOEngineName.startsWith("heap")) {
    float bucketCachePercentage = conf.getFloat(HConstants.BUCKET_CACHE_SIZE_KEY, 0F);
    MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    l2CachePercent = bucketCachePercentage < 1 ? bucketCachePercentage
        : (bucketCachePercentage * 1024 * 1024) / mu.getMax();
  }
  return l2CachePercent;
}
 
Example 22
Project: asura   File: QuartzScheduler.java   View source code 5 votes vote down vote up
/**
 * Register the scheduler in the local MBeanServer.
 */
private void registerJMX() throws Exception {
	String jmxObjectName = resources.getJMXObjectName();
	MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
	jmxBean = new QuartzSchedulerMBeanImpl(this);
	mbs.registerMBean(jmxBean, new ObjectName(jmxObjectName));
}
 
Example 23
Project: openjdk-jdk10   File: ParallelPrefix.java   View source code 5 votes vote down vote up
@BeforeSuite
public static void setup() {
    java.lang.management.OperatingSystemMXBean bean =
            ManagementFactory.getOperatingSystemMXBean();
    if (bean instanceof OperatingSystemMXBean) {
        OperatingSystemMXBean os = (OperatingSystemMXBean)bean;
        long physicalMemorySize = os.getTotalPhysicalMemorySize() / (1024 * 1024);
        System.out.println("System memory size: " + physicalMemorySize + "M");
        // when we can get system memory size, and it's larger than 2G,
        // then we enable large array size test below,
        // else disable large array size test below.
        if (physicalMemorySize > (2 * 1024)) {
            arraySizeCollection  = new int[]{
                    SMALL_ARRAY_SIZE,
                    THRESHOLD_ARRAY_SIZE,
                    MEDIUM_ARRAY_SIZE,
                    LARGE_ARRAY_SIZE
                };
            System.out.println("System memory is large enough, add large array size test");
            return;
        }
    }
    arraySizeCollection  = new int[]{
            SMALL_ARRAY_SIZE,
            THRESHOLD_ARRAY_SIZE,
            MEDIUM_ARRAY_SIZE
        };
    System.out.println("System memory is not large enough, remove large array size test");
}
 
Example 24
Project: java-performance   File: Threads.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
    System.out.println("Threads");
    ThreadMXBean threadMBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();

    System.out.println("Thread count = " + threadMBean.getThreadCount());
    System.out.println("Thread IDs = " + Arrays.toString(threadMBean.getAllThreadIds()));

    System.out.println(">>>>> Thread INFO");
    ThreadInfo[] threads = threadMBean.dumpAllThreads(true, true);
    for (ThreadInfo thread : threads) {
        System.out.println(thread);
    }

    System.out.println(">>>>> Thread INFO detailed");
    for (long threadId : threadMBean.getAllThreadIds()) {
        ThreadInfo threadInfo = threadMBean.getThreadInfo(threadId, 100);
        long cpuTime = threadMBean.getThreadCpuTime(threadId);
        long userTime = threadMBean.getThreadUserTime(threadId);
        long allocatedBytes = threadMBean.getThreadAllocatedBytes(threadId);
        System.out.println(threadInfo);
        System.out.println("CPU Time: " + cpuTime + ", USER time: " + userTime + ", Allocated bytes: " + allocatedBytes);
    }

    // Getting stack-traces of the current thread
    System.out.print(">> current thread: " + Thread.currentThread().getName() + "\n");
    for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
        System.out.println(element);
    }
}
 
Example 25
Project: jdk8u-jdk   File: InvalidThreadID.java   View source code 5 votes vote down vote up
public static void main(String argv[]) {

        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
        int cnt = 0;
        long [] idArr = {0, -1, -2, (Long.MIN_VALUE + 1), Long.MIN_VALUE};

        if (mbean.isThreadCpuTimeSupported()) {
            for (int i = 0; i < idArr.length; i++) {
                try {
                    mbean.getThreadCpuTime(idArr[i]);
                    System.out.println("Test failed. IllegalArgumentException" +
                        " expected for ID = " + idArr[i]);
                } catch (IllegalArgumentException iae) {
                    cnt++;
                }
            }
            if (cnt != idArr.length) {
                throw new RuntimeException("Unexpected number of " +
                    "IllegalArgumentException = " + cnt +
                    " expected = " + idArr.length);
            }

            // CPU time for a non-existence thread
            long time = mbean.getThreadCpuTime(999999);
            if (time < 0 && time != -1) {
                throw new RuntimeException("Cpu time for thread 999999" +
                    " is invalid = " + time + " expected to be -1.");
            }
        }
        System.out.println("Test passed.");
    }
 
Example 26
Project: jdk8u-jdk   File: RedefineMethodInBacktraceApp.java   View source code 5 votes vote down vote up
private void doMethodInBacktraceTestB() throws Exception {
    // Start a thread which blocks in method
    Thread t = new Thread(RedefineMethodInBacktraceTargetB::methodToRedefine);
    t.setDaemon(true);
    t.start();

    // Wait here until the new thread is in the method we want to redefine
    called.await();

    // Now redefine the class while the method is still on the stack of the new thread
    doRedefine(RedefineMethodInBacktraceTargetB.class);

    // Do thread dumps in two different ways (to exercise different code paths)
    // while the old class is still on the stack

    ThreadInfo[] tis = ManagementFactory.getThreadMXBean().dumpAllThreads(false, false);
    for(ThreadInfo ti : tis) {
        System.out.println(ti);
    }

    String[] threadPrintArgs = {};
    Object[] dcmdArgs = {threadPrintArgs};
    String[] signature = {String[].class.getName()};
    DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
    System.out.println(dcmd.invoke("threadPrint", dcmdArgs, signature));

    // release the thread
    stop.countDown();
}
 
Example 27
Project: hashsdn-controller   File: ConfigTransactionControllerImplTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
    transactionsMBeanServer = MBeanServerFactory.createMBeanServer();
    Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories = new HashMap<>();

    ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(
            new TransactionIdentifier(TRANSACTION_NAME123),
        () -> baseJMXRegistrator.createTransactionJMXRegistrator(TRANSACTION_NAME123),
        currentlyRegisteredFactories);

    SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl
            .createSRWritableRegistry(ServiceReferenceRegistryImpl.createInitialSRLookupRegistry(),
                    txLookupRegistry, currentlyRegisteredFactories);

    testedTxController = new ConfigTransactionControllerImpl(txLookupRegistry, 1, null, 1,
            currentlyRegisteredFactories, transactionsMBeanServer, ManagementFactory.getPlatformMBeanServer(),
            false, writableRegistry);
    TransactionModuleJMXRegistrator transactionModuleJMXRegistrator123 = testedTxController
            .getTxModuleJMXRegistrator();
    transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME1);
    transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME2);
    transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME3);
    TransactionJMXRegistrator jmxRegistrator4 = baseJMXRegistrator
            .createTransactionJMXRegistrator(TRANSACTION_NAME4);
    jmxRegistrator4.createTransactionModuleJMXRegistrator().registerMBean(new TestingRuntimeBean(), NAME4);
}
 
Example 28
Project: lams   File: QuartzScheduler.java   View source code 5 votes vote down vote up
/**
 * Register the scheduler in the local MBeanServer.
 */
private void registerJMX() throws Exception {
    String jmxObjectName = resources.getJMXObjectName();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    jmxBean = new QuartzSchedulerMBeanImpl(this);
    mbs.registerMBean(jmxBean, new ObjectName(jmxObjectName));
}
 
Example 29
Project: fuck_zookeeper   File: OSMXBean.java   View source code 5 votes vote down vote up
/**
 * Get the number of opened filed descriptor for the runtime jvm.
 * If sun java, it will use the com.sun.management interfaces.
 * Otherwise, this methods implements it (linux only).  
 * @return number of open file descriptors for the jvm
 */
public long getOpenFileDescriptorCount() 
{
    Long ofdc;

    if (!ibmvendor) {
        ofdc = getOSUnixMXBeanMethod("getOpenFileDescriptorCount");
        return (ofdc != null ? ofdc.longValue () : -1);
    }
    
    try {
        //need to get the PID number of the process first
        RuntimeMXBean rtmbean = ManagementFactory.getRuntimeMXBean();
        String rtname = rtmbean.getName();
        String[] pidhost = rtname.split("@");

        //using linux bash commands to retrieve info
        Process p = Runtime.getRuntime().exec(
                new String[] { "bash", "-c",
                "ls /proc/" + pidhost[0] + "/fdinfo | wc -l" });
        InputStream in = p.getInputStream();
        BufferedReader output = new BufferedReader(
                new InputStreamReader(in));

        try {
            String openFileDesCount;
            if ((openFileDesCount = output.readLine()) != null) {
                return Long.parseLong(openFileDesCount);
            }
        } finally {
            if (output != null) {
                output.close();
            }
        }
    } catch (IOException ie) {
        LOG.warn("Not able to get the number of open file descriptors", ie);
    }
    return -1;
}
 
Example 30
Project: javametrics   File: MemoryPoolDataProvider.java   View source code 5 votes vote down vote up
private static long getMemory(MemoryType type, MemoryValue memval) {
    long total = 0;
    List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans();
    if (memoryPoolBeans.isEmpty()) {
        return -1;
    }
    for (Iterator<MemoryPoolMXBean> iterator = memoryPoolBeans.iterator(); iterator.hasNext();) {
        MemoryPoolMXBean memoryPoolMXBean = iterator.next();
        if (memoryPoolMXBean.getType().equals(type)) {
            total += memval.getValue(memoryPoolMXBean);
        }
    }
    return total;
}
 
Example 31
Project: xm-ms-balance   File: MetricsConfiguration.java   View source code 5 votes vote down vote up
@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");
        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 32
Project: jdk8u-jdk   File: MXBeanInteropTest1.java   View source code 5 votes vote down vote up
private final int doClassLoadingMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- ClassLoadingMXBean") ;

    try {
        ObjectName classLoadingName =
                new ObjectName(ManagementFactory.CLASS_LOADING_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(classLoadingName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t"
                + mbInfo);
        ClassLoadingMXBean classLoading = null;

        classLoading = JMX.newMXBeanProxy(mbsc,
                classLoadingName,
                ClassLoadingMXBean.class) ;
        System.out.println("getLoadedClassCount\t\t"
                + classLoading.getLoadedClassCount());
        System.out.println("getTotalLoadedClassCount\t\t"
                + classLoading.getTotalLoadedClassCount());
        System.out.println("getUnloadedClassCount\t\t"
                + classLoading.getUnloadedClassCount());
        System.out.println("isVerbose\t\t"
                + classLoading.isVerbose());

        System.out.println("---- OK\n") ;

    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example 33
Project: L2J-Global   File: GameServer.java   View source code 5 votes vote down vote up
public String getUptime()
{
	final long uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000;
	final long hours = uptime / 3600;
	final long mins = (uptime - (hours * 3600)) / 60;
	final long secs = ((uptime - (hours * 3600)) - (mins * 60));
	if (hours > 0)
	{
		return hours + "hrs " + mins + "mins " + secs + "secs";
	}
	return mins + "mins " + secs + "secs";
}
 
Example 34
Project: hadoop   File: GenericTestUtils.java   View source code 5 votes vote down vote up
/**
 * Assert that there are no threads running whose name matches the
 * given regular expression.
 * @param regex the regex to match against
 */
public static void assertNoThreadsMatching(String regex) {
  Pattern pattern = Pattern.compile(regex);
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  
  ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
  for (ThreadInfo info : infos) {
    if (info == null) continue;
    if (pattern.matcher(info.getThreadName()).matches()) {
      Assert.fail("Leaked thread: " + info + "\n" +
          Joiner.on("\n").join(info.getStackTrace()));
    }
  }
}
 
Example 35
Project: openjdk-jdk10   File: MXBeanWeirdParamTest.java   View source code 5 votes vote down vote up
private JMXServiceURL createServerSide() throws Exception {
    final int NINETY_SECONDS = 90;

    // We will use the platform mbean server
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();

    Utils.waitReady(cs, NINETY_SECONDS);

    JMXServiceURL addr = cs.getAddress();
    return addr;
}
 
Example 36
Project: OpenVertretung   File: LoadBalanceConnectionGroupManager.java   View source code 5 votes vote down vote up
public synchronized void registerJmx() throws SQLException {
    if (this.isJmxRegistered) {
        return;
    }
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName name = new ObjectName("com.mysql.jdbc.jmx:type=LoadBalanceConnectionGroupManager");
        mbs.registerMBean(this, name);
        this.isJmxRegistered = true;
    } catch (Exception e) {
        throw SQLError.createSQLException("Unable to register load-balance management bean with JMX", null, e, null);
    }

}
 
Example 37
Project: openjdk-jdk10   File: GetDiagnosticOptions.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    List<HotSpotDiagnosticMXBean> list =
        ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
    HotSpotDiagnosticMXBean mbean = list.get(0);
    checkDiagnosticOptions(mbean);

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    mbean = ManagementFactory.newPlatformMXBeanProxy(mbs,
                HOTSPOT_DIAGNOSTIC_MXBEAN_NAME,
                HotSpotDiagnosticMXBean.class);
    checkDiagnosticOptions(mbean);
}
 
Example 38
Project: minebox   File: TransmissionPhase.java   View source code 5 votes vote down vote up
public TransmissionPhase(MinebdConfig config, ExportProvider exportProvider) {
    super();
    this.maxUnflushedBytes = config.maxUnflushed.toBytes();
    this.minFreeSystemMem = config.minFreeSystemMem.toBytes();
    this.exportProvider = exportProvider;
    executor = new BlockingExecutor(10, 20);
    osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
}
 
Example 39
Project: openjdk-jdk10   File: AnnotationTypeDeadlockTest.java   View source code 5 votes vote down vote up
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 40
Project: Android_Code_Arbiter   File: VerboseTestListener.java   View source code 5 votes vote down vote up
@Override
public void onFinish(ITestContext ctx) {
    System.gc();
    Runtime rt = Runtime.getRuntime();
    long inMb = 1024 * 1024;
    log.info("Total memory : " + rt.totalMemory() / inMb);
    log.info("Free memory  : " + rt.freeMemory() / inMb);
    log.info("Memory usage : " + (rt.totalMemory() - rt.freeMemory()) / inMb);
    log.info("Process      : " + ManagementFactory.getRuntimeMXBean().getName());
    log.info("<<<<<<<<<<<<<<<<<<<< {} finished >>>>>>>>>>>>>>>>>>>>", ctx.getName());
}