Java Code Examples for java.lang.management.ManagementFactory.getThreadMXBean()

The following are Jave code examples for showing how to use getThreadMXBean() of the java.lang.management.ManagementFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-servicecomb-java-chassis   File: MetricsServoRegistry.java   View Source Code Vote up 6 votes
@Override
public String call() {
  Map<String, String> memoryMap = new HashMap<>();
  OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
  double cpu = osMxBean.getSystemLoadAverage();
  memoryMap.put("cpuLoad", String.format(doubleStringFormatter, round(cpu, doubleRoundPlaces)));

  ThreadMXBean threadmxBean = ManagementFactory.getThreadMXBean();
  int threadCount = threadmxBean.getThreadCount();
  memoryMap.put("cpuRunningThreads", String.valueOf(threadCount));

  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage memHeapUsage = memBean.getHeapMemoryUsage();
  MemoryUsage nonHeapUsage = memBean.getNonHeapMemoryUsage();
  memoryMap.put("heapInit", String.valueOf(memHeapUsage.getInit()));
  memoryMap.put("heapMax", String.valueOf(memHeapUsage.getMax()));
  memoryMap.put("heapCommit", String.valueOf(memHeapUsage.getCommitted()));
  memoryMap.put("heapUsed", String.valueOf(memHeapUsage.getUsed()));
  memoryMap.put("nonHeapInit", String.valueOf(nonHeapUsage.getInit()));
  memoryMap.put("nonHeapMax", String.valueOf(nonHeapUsage.getMax()));
  memoryMap.put("nonHeapCommit", String.valueOf(nonHeapUsage.getCommitted()));
  memoryMap.put("nonHeapUsed", String.valueOf(nonHeapUsage.getUsed()));
  return memoryMap.toString();
}
 
Example 2
Project: ats-framework   File: ThreadUtils.java   View Source Code Vote up 6 votes
/**
 * @return Set of the IDs of all threads that are started except the "main" thread.
 */
public Set<Long> getAllThreadIDsExceptMain() {

    ThreadMXBean thbean = ManagementFactory.getThreadMXBean();
    // get the IDs of all live threads.
    long[] threadIDs = thbean.getAllThreadIds();
    Set<Long> res = new HashSet<Long>();

    // get the IDs of all threads except main
    for (long id : threadIDs) {
        Thread t = getThread(id);
        if (t != null && !"main".equals(t.getName())) {
            res.add(id);
        }
    }

    return res;
}
 
Example 3
Project: hadoop   File: TimedOutTestsListener.java   View Source Code Vote up 6 votes
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 4
Project: hadoop   File: TestShell.java   View Source Code Vote up 6 votes
private static int countTimerThreads() {
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  
  int count = 0;
  ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
  for (ThreadInfo info : infos) {
    if (info == null) continue;
    for (StackTraceElement elem : info.getStackTrace()) {
      if (elem.getClassName().contains("Timer")) {
        count++;
        break;
      }
    }
  }
  return count;
}
 
Example 5
Project: incubator-netbeans   File: StackTraceSnapshotBuilderTest.java   View Source Code Vote up 6 votes
@Test
public void testReset() {
    System.out.println("reset");
    ThreadMXBean tbean = ManagementFactory.getThreadMXBean();
    addStacktrace(tbean.getThreadInfo(tbean.getAllThreadIds(), Integer.MAX_VALUE), System.nanoTime());
    addStacktrace(tbean.getThreadInfo(tbean.getAllThreadIds(), Integer.MAX_VALUE), System.nanoTime());

    instance.reset();
    assertTrue(instance.methodInfos.size()-1 == 0);
    assertTrue(instance.threadIds.size() == 0);
    assertTrue(instance.threadNames.size() == 0);
    assertEquals(-1L, instance.currentDumpTimeStamp);
    //assertEquals(-1L, instance.firstDumpTimeStamp);
    assertEquals(0, instance.stackTraceCount);

    try {
        instance.createSnapshot(System.currentTimeMillis());
        fail();
    } catch (CPUResultsSnapshot.NoDataAvailableException ex) {
    }
}
 
Example 6
Project: ats-framework   File: ThreadUtils.java   View Source Code Vote up 6 votes
/**
 * @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 7
Project: openjdk-jdk10   File: ConcurrentAssociateTest.java   View Source Code Vote up 6 votes
/**
 * 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 8
Project: openjdk-jdk10   File: GetInternalThreads.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
    long value = mbean.getInternalThreadCount();

    if (value < MIN_VALUE_FOR_PASS || value > MAX_VALUE_FOR_PASS) {
        throw new RuntimeException("Internal thread count " +
                                   "illegal value: " + value + " " +
                                   "(MIN = " + MIN_VALUE_FOR_PASS + "; " +
                                   "MAX = " + MAX_VALUE_FOR_PASS + ")");
    }

    System.out.println("Internal Thread Count = " + value);

    ThreadMXBean thread =
        ManagementFactory.getThreadMXBean();
    if (!thread.isThreadCpuTimeSupported()) {
        System.out.println("Thread Cpu Time is not supported.");
        return;
    }

    while(!testCPUTime()) {
        Thread.sleep(100);
    }
}
 
Example 9
Project: hadoop-oss   File: TimedOutTestsListener.java   View Source Code Vote up 6 votes
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 10
Project: hadoop-oss   File: TestRpcBase.java   View Source Code Vote up 6 votes
/**
 * Count the number of threads that have a stack frame containing
 * the given string
 */
protected static int countThreads(String search) {
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

  int count = 0;
  ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
  for (ThreadInfo info : infos) {
    if (info == null) continue;
    for (StackTraceElement elem : info.getStackTrace()) {
      if (elem.getClassName().contains(search)) {
        count++;
        break;
      }
    }
  }
  return count;
}
 
Example 11
Project: cornerstone   File: ThreadingManager.java   View Source Code Vote up 6 votes
public static ThreadInfo[] dump(int maxDepth,boolean onlyDeadLock){
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    long[] ids ;
    if(onlyDeadLock) {
        ids = threadBean.findDeadlockedThreads();
    }else {
       ids = threadBean.getAllThreadIds();
    }
    if(ids !=null) {
        return threadBean.getThreadInfo(ids, maxDepth);
    }
    else {
        return null;
    }


}
 
Example 12
Project: PEF   File: PcapSniffer.java   View Source Code Vote up 5 votes
/**
 * Initialization of the pseudo packet handler which measures the time to handle the configured amount of bytes.
 *
 * @param pcap the interface with the pcap library needed to construct the packet handler.
 * @param MAX_BYTES the maximum amount of bytes captured
 * @return the handler for the packets.
 */
private static PcapPacketHandler<PseudoPacketHandler> getTimedByteLimitedHandler(final Pcap pcap, final long MAX_BYTES) {
    // Packet handler. Generic callback function for PseudoPacketHandler.
    return new PcapPacketHandler<PseudoPacketHandler>() {
        boolean started = false;
        long packetBytes = 0;
        long startTime;
        long stopTime;

        // A timer for performance tests.
        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        // Handle nextPacket callback.
        public void nextPacket(PcapPacket packet, PseudoPacketHandler handler) {
            if (!started) {
                startTime = threadMXBean.getCurrentThreadCpuTime();
                logger.info("Started at "+ startTime);
                started = true;
            }
            handler.handle(packet);

            packetBytes+= packet.size();
            if (packetBytes >= MAX_BYTES) {
                stopTime = threadMXBean.getCurrentThreadCpuTime();
                pcap.breakloop();
                logger.info("Stopped after " + ((stopTime - startTime)/10000000000.0) + " seconds and " + packetBytes + " bytes.");
            }
        }
    };
}
 
Example 13
Project: rskj   File: VMExecutionTest.java   View Source Code Vote up 5 votes
@Test
public void thePathOfFifteenThousandJumps() {
    byte[] bytecode = new byte[15000 * 6 + 3];

    int k = 0;

    while (k < 15000 * 6) {
        int target = k + 6;
        bytecode[k++] = 0x5b; // JUMPDEST
        bytecode[k++] = 0x62; // PUSH3
        bytecode[k++] = (byte)(target >> 16);
        bytecode[k++] = (byte)(target >> 8);
        bytecode[k++] = (byte)(target & 0xff);
        bytecode[k++] = 0x56; // JUMP
    }

    bytecode[k++] = 0x5b; // JUMPDEST
    bytecode[k++] = 0x60; // PUSH1
    bytecode[k++] = 0x01; // 1

    ThreadMXBean thread = ManagementFactory.getThreadMXBean();

    Runtime runtime = Runtime.getRuntime();
    runtime.gc();
    long initialMemory = runtime.totalMemory() - runtime.freeMemory();
    long initialTime = thread.getCurrentThreadCpuTime();
    testCode(bytecode, 15000 * 3 + 2, "0000000000000000000000000000000000000000000000000000000000000001");
    long finalTime = thread.getCurrentThreadCpuTime();
    long finalMemory = runtime.totalMemory() - runtime.freeMemory();

    System.out.println(String.format("Execution Time %s nanoseconds", finalTime - initialTime));
    System.out.println(String.format("Delta memory %s", finalMemory - initialMemory));
}
 
Example 14
Project: jdk8u-jdk   File: TestThread.java   View Source Code Vote up 5 votes
/**
 * Waits until {@link TestThread} is in native.
 */
public void waitUntilInNative() {
    ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
    while (isAlive()) {
        ThreadInfo ti = tmx.getThreadInfo(getId());
        if (ti.isInNative()) {
            return;
        }
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }
}
 
Example 15
Project: jsf-sdk   File: JVMStatusTelnetHandler.java   View Source Code Vote up 5 votes
@Override
   public String telnet(Channel channel, String message) {
	StringBuilder sb = new StringBuilder();
	//内存使用情况
       MemoryMXBean mmxb = ManagementFactory.getMemoryMXBean();
       long max = mmxb.getHeapMemoryUsage().getMax();
       long used = mmxb.getHeapMemoryUsage().getUsed();
       long init = mmxb.getHeapMemoryUsage().getInit();
       long commit = mmxb.getHeapMemoryUsage().getCommitted();
       sb.append("********Memory status******************").append(line);
       sb.append("Max JVM Heap Memory:").append(max / 1024 / 1024).append("M").append(line)
               .append("Used Heap Memory:").append(used / 1024 / 1024).append("M").append(line)
               .append("Init Heap Memory:").append(init / 1024 / 1024).append("M").append(line)
               .append("Commited Heap Memory:").append(commit/1024/1024).append("M").append(line);
       
       sb.append("********Thread status********************").append(line);
       //线程数
       ThreadMXBean txmb = ManagementFactory.getThreadMXBean();
       sb.append("Peak thread count:").append(txmb.getPeakThreadCount()).append("").append(line)
               .append("Thread count:").append(txmb.getThreadCount()).append("").append(line);

       sb.append("********Runtime status******************").append(line);
       //启动入口参数
       RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
       sb.append("InputArguments:[");
       for(String ia : rmxb.getInputArguments()){
       	sb.append(ia).append(",");
       }
       sb.deleteCharAt(sb.length()-1).append("]").append(line);
       sb.append("JVM start time:").append(DateUtils.dateToStr(new Date(rmxb.getStartTime()))).append(line);
       
       return sb.toString();
}
 
Example 16
Project: openjdk-jdk10   File: SurvivorAlignmentTestMain.java   View Source Code Vote up 5 votes
/**
 * Checks if threads other then the current thread were allocating objects
 * after baselinedThreadMemoryUsage call.
 *
 * If baselinedThreadMemoryUsage was not called, then this method will return
 * {@code false}.
 */
public boolean areOtherThreadsAllocatedMemory() {
    if (baselinedThreadMemoryUsage == null) {
        return false;
    }

    ThreadMXBean bean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
    long currentMemoryAllocation[]
            = bean.getThreadAllocatedBytes(threadIds);
    boolean otherThreadsAllocatedMemory = false;

    System.out.println("Verifying amount of memory allocated by threads:");
    for (int i = 0; i < threadIds.length; i++) {
        System.out.format("Thread %d%nbaseline allocation: %d"
                        + "%ncurrent allocation:%d%n", threadIds[i],
                baselinedThreadMemoryUsage[i], currentMemoryAllocation[i]);
        System.out.println(bean.getThreadInfo(threadIds[i]));

        long bytesAllocated = Math.abs(currentMemoryAllocation[i]
                - baselinedThreadMemoryUsage[i]);
        if (bytesAllocated > 0
                && threadIds[i] != Thread.currentThread().getId()) {
            otherThreadsAllocatedMemory = true;
        }
    }

    return otherThreadsAllocatedMemory;
}
 
Example 17
Project: CustomWorldGen   File: ServerHangWatchdog.java   View Source Code Vote up 4 votes
public void run()
{
    while (this.server.isServerRunning())
    {
        long i = this.server.getCurrentTime();
        long j = MinecraftServer.getCurrentTimeMillis();
        long k = j - i;

        if (k > this.maxTickTime && !this.firstRun)
        {
            LOGGER.fatal("A single server tick took {} seconds (should be max {})", new Object[] {String.format("%.2f", new Object[]{Float.valueOf((float)k / 1000.0F)}), String.format("%.2f", new Object[]{Float.valueOf(0.05F)})});
            LOGGER.fatal("Considering it to be crashed, server will forcibly shutdown.");
            ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean();
            ThreadInfo[] athreadinfo = threadmxbean.dumpAllThreads(true, true);
            StringBuilder stringbuilder = new StringBuilder();
            Error error = new Error();

            for (ThreadInfo threadinfo : athreadinfo)
            {
                if (threadinfo.getThreadId() == this.server.getServerThread().getId())
                {
                    error.setStackTrace(threadinfo.getStackTrace());
                }

                stringbuilder.append((Object)threadinfo);
                stringbuilder.append("\n");
            }

            CrashReport crashreport = new CrashReport("Watching Server", error);
            this.server.addServerInfoToCrashReport(crashreport);
            CrashReportCategory crashreportcategory = crashreport.makeCategory("Thread Dump");
            crashreportcategory.addCrashSection("Threads", stringbuilder);
            File file1 = new File(new File(this.server.getDataDirectory(), "crash-reports"), "crash-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + "-server.txt");

            if (crashreport.saveToFile(file1))
            {
                LOGGER.error("This crash report has been saved to: {}", new Object[] {file1.getAbsolutePath()});
            }
            else
            {
                LOGGER.error("We were unable to save this crash report to disk.");
            }

            this.scheduleHalt();
        }

        this.firstRun = false;

        try
        {
            Thread.sleep(i + this.maxTickTime - j);
        }
        catch (InterruptedException var15)
        {
            ;
        }
    }
}
 
Example 18
Project: tqdev-metrics   File: SystemMonitor.java   View Source Code Vote up 4 votes
private void registerThreadStatistics() {
	final ThreadMXBean thread = ManagementFactory.getThreadMXBean();
	registry.set("jvm.Thread.Count", "total", (Gauge) () -> thread.getThreadCount());
	registry.set("jvm.Thread.Count", "daemon", (Gauge) () -> thread.getDaemonThreadCount());
}
 
Example 19
Project: incubator-netbeans   File: InternalSampler.java   View Source Code Vote up 4 votes
@Override
ThreadMXBean getThreadMXBean() {
    return ManagementFactory.getThreadMXBean();
}
 
Example 20
Project: BibliotecaPS   File: ResultSetRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests fix for Bug#70704 - Deadlock using UpdatableResultSet.
 * 
 * Doesn't actually test the buggy behavior since it is not verifiable since the fix for Bug#59462 (revision 385a151). However, the patch for this fix is
 * needed because the synchronization in UpdatableResultSet was dated.
 * This test makes sure there is no regression.
 * 
 * WARNING! If this test fails there is no guarantee that the JVM will remain stable and won't affect any other tests. It is imperative that this test
 * passes to ensure other tests results.
 */
public void testBug70704() throws Exception {
    for (int i = 0; i < 100; i++) {
        final Statement testStmt = this.conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        final ResultSet testRs = testStmt.executeQuery("SELECT 1");

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(new Callable<Void>() {
            public Void call() throws Exception {
                testStmt.close();
                return null;
            }
        });

        executorService.submit(new Callable<Void>() {
            public Void call() throws Exception {
                testRs.close();
                return null;
            }
        });

        executorService.shutdown();
        if (!executorService.awaitTermination(2, TimeUnit.SECONDS)) {
            ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
            long[] threadIds = threadMXBean.findMonitorDeadlockedThreads();
            if (threadIds != null) {
                System.err.println("Deadlock detected!");
                ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
                for (ThreadInfo ti : threadInfos) {
                    System.err.println();
                    System.err.println(ti);
                    System.err.println("Stack trace:");
                    for (StackTraceElement ste : ti.getStackTrace()) {
                        System.err.println("   " + ste);
                    }
                }
                fail("Unexpected deadlock detected. Consult system output for more details. WARNING: this failure may lead to JVM instability.");
            }
        }
    }
}