Java Code Examples for java.lang.management.ThreadMXBean#getAllThreadIds()

The following examples show how to use java.lang.management.ThreadMXBean#getAllThreadIds() . 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: OSProcess.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/** dumps this vm's stacks and returns gzipped result */
public static byte[] zipStacks() throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream(10000);
  GZIPOutputStream zipOut = new GZIPOutputStream(baos, 10000);
  PrintWriter pw = new PrintWriter(zipOut, true);
  final GemFireCacheImpl.StaticSystemCallbacks sysCb = GemFireCacheImpl
      .getInternalProductCallbacks();
  if (sysCb == null) {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    long[] threadIds = bean.getAllThreadIds();
    ThreadInfo[] infos = bean.getThreadInfo(threadIds, true, true);
    long thisThread = Thread.currentThread().getId();
    for (int i = 0; i < infos.length; i++) {
      if (i != thisThread  &&  infos[i] != null) {
        formatThreadInfo(infos[i], pw);
      }
    }
  }
  else {
    sysCb.printStacks(pw);
  }
  pw.flush();
  zipOut.close();
  byte[] result = baos.toByteArray();
  return result;
}
 
Example 2
Source File: ThreadLists.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) {

        // get top-level thread group
        ThreadGroup top = Thread.currentThread().getThreadGroup();
        ThreadGroup parent;
        do {
            parent = top.getParent();
            if (parent != null) top = parent;
        } while (parent != null);

        // get the thread count
        int activeCount = top.activeCount();

        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();

        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        int threadCount = threadBean.getThreadCount();
        long[] threadIds = threadBean.getAllThreadIds();

        System.out.println("ThreadGroup: " + activeCount + " active thread(s)");
        System.out.println("Thread: " + stackTraces.size() + " stack trace(s) returned");
        System.out.println("ThreadMXBean: " + threadCount + " live threads(s)");
        System.out.println("ThreadMXBean: " + threadIds.length + " thread Id(s)");

        // check results are consistent
        boolean failed = false;
        if (activeCount != stackTraces.size()) failed = true;
        if (activeCount != threadCount) failed = true;
        if (activeCount != threadIds.length) failed = true;

        if (failed) {
            throw new RuntimeException("inconsistent results");
        }
    }
 
Example 3
Source File: ThreadLists.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) {

        // Bug id : JDK-8151797
        // Use a lambda expression so that call-site cleaner thread is started
        Runnable printLambda = () -> {System.out.println("Starting Test");};
        printLambda.run();

        // get top-level thread group
        ThreadGroup top = Thread.currentThread().getThreadGroup();
        ThreadGroup parent;
        do {
            parent = top.getParent();
            if (parent != null) top = parent;
        } while (parent != null);

        // get the thread count
        int activeCount = top.activeCount();

        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();

        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        int threadCount = threadBean.getThreadCount();
        long[] threadIds = threadBean.getAllThreadIds();

        System.out.println("ThreadGroup: " + activeCount + " active thread(s)");
        System.out.println("Thread: " + stackTraces.size() + " stack trace(s) returned");
        System.out.println("ThreadMXBean: " + threadCount + " live threads(s)");
        System.out.println("ThreadMXBean: " + threadIds.length + " thread Id(s)");

        // check results are consistent
        boolean failed = false;
        if (activeCount != stackTraces.size()) failed = true;
        if (activeCount != threadCount) failed = true;
        if (activeCount != threadIds.length) failed = true;

        if (failed) {
            throw new RuntimeException("inconsistent results");
        }
    }
 
Example 4
Source File: ThreadLists.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) {

        // get top-level thread group
        ThreadGroup top = Thread.currentThread().getThreadGroup();
        ThreadGroup parent;
        do {
            parent = top.getParent();
            if (parent != null) top = parent;
        } while (parent != null);

        // get the thread count
        int activeCount = top.activeCount();

        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();

        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        int threadCount = threadBean.getThreadCount();
        long[] threadIds = threadBean.getAllThreadIds();

        System.out.println("ThreadGroup: " + activeCount + " active thread(s)");
        System.out.println("Thread: " + stackTraces.size() + " stack trace(s) returned");
        System.out.println("ThreadMXBean: " + threadCount + " live threads(s)");
        System.out.println("ThreadMXBean: " + threadIds.length + " thread Id(s)");

        // check results are consistent
        boolean failed = false;
        if (activeCount != stackTraces.size()) failed = true;
        if (activeCount != threadCount) failed = true;
        if (activeCount != threadIds.length) failed = true;

        if (failed) {
            throw new RuntimeException("inconsistent results");
        }
    }
 
Example 5
Source File: TPerformance.java    From Voovan with Apache License 2.0 5 votes vote down vote up
/**
 * 获取当前进程 cpu 使用量
 * @return cpu 使用量, 如使用2核, 返回200%
 */
public static double getProcessCpuUsage() {
	ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
	long totalCpuUsedTime = 0;
	for (long id : threadBean.getAllThreadIds()) {
		totalCpuUsedTime += threadBean.getThreadCpuTime(id);
	}
	long curtime = System.nanoTime();
	long usedTime = totalCpuUsedTime - prevCpuUsedTime; //cpu 用时差
	long totalPassedTime = curtime - prevGetTime; //时间差
	prevGetTime = curtime;
	prevCpuUsedTime = totalCpuUsedTime;
	return (((double) usedTime) / totalPassedTime) * 100;
}
 
Example 6
Source File: QueryMasterRunner.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
public static void printThreadInfo(PrintWriter stream, String title) {
  ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  final int STACK_DEPTH = 60;
  boolean contention = threadBean.isThreadContentionMonitoringEnabled();
  long[] threadIds = threadBean.getAllThreadIds();
  stream.println("Process Thread Dump: " + title);
  stream.println(threadIds.length + " active threads");
  for (long tid : threadIds) {
    ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH);
    if (info == null) {
      stream.println("  Inactive");
      continue;
    }
    stream.println("Thread " + getTaskName(info.getThreadId(), info.getThreadName()) + ":");
    Thread.State state = info.getThreadState();
    stream.println("  State: " + state);
    stream.println("  Blocked count: " + info.getBlockedCount());
    stream.println("  Waited count: " + info.getWaitedCount());
    if (contention) {
      stream.println("  Blocked time: " + info.getBlockedTime());
      stream.println("  Waited time: " + info.getWaitedTime());
    }
    if (state == Thread.State.WAITING) {
      stream.println("  Waiting on " + info.getLockName());
    } else if (state == Thread.State.BLOCKED) {
      stream.println("  Blocked on " + info.getLockName());
      stream.println("  Blocked by " + getTaskName(info.getLockOwnerId(), info.getLockOwnerName()));
    }
    stream.println("  Stack:");
    for (StackTraceElement frame : info.getStackTrace()) {
      stream.println("    " + frame.toString());
    }
  }
  stream.flush();
}
 
Example 7
Source File: ThreadLists.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) {

        // get top-level thread group
        ThreadGroup top = Thread.currentThread().getThreadGroup();
        ThreadGroup parent;
        do {
            parent = top.getParent();
            if (parent != null) top = parent;
        } while (parent != null);

        // get the thread count
        int activeCount = top.activeCount();

        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();

        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        int threadCount = threadBean.getThreadCount();
        long[] threadIds = threadBean.getAllThreadIds();

        System.out.println("ThreadGroup: " + activeCount + " active thread(s)");
        System.out.println("Thread: " + stackTraces.size() + " stack trace(s) returned");
        System.out.println("ThreadMXBean: " + threadCount + " live threads(s)");
        System.out.println("ThreadMXBean: " + threadIds.length + " thread Id(s)");

        // check results are consistent
        boolean failed = false;
        if (activeCount != stackTraces.size()) failed = true;
        if (activeCount != threadCount) failed = true;
        if (activeCount != threadIds.length) failed = true;

        if (failed) {
            throw new RuntimeException("inconsistent results");
        }
    }
 
Example 8
Source File: LogicalIOProcessorRuntimeTask.java    From tez with Apache License 2.0 5 votes vote down vote up
/**
 * Print all threads in JVM (only for debugging)
 */
void printThreads() {
  //Print the status of all threads in JVM
  ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  long[] threadIds = threadMXBean.getAllThreadIds();
  for (Long id : threadIds) {
    ThreadInfo threadInfo = threadMXBean.getThreadInfo(id);
    // The thread could have been shutdown before we read info about it.
    if (threadInfo != null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("ThreadId : " + id + ", name=" + threadInfo.getThreadName());
      }
    }
  }
}
 
Example 9
Source File: ThreadLists.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) {

        // get top-level thread group
        ThreadGroup top = Thread.currentThread().getThreadGroup();
        ThreadGroup parent;
        do {
            parent = top.getParent();
            if (parent != null) top = parent;
        } while (parent != null);

        // get the thread count
        int activeCount = top.activeCount();

        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();

        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        int threadCount = threadBean.getThreadCount();
        long[] threadIds = threadBean.getAllThreadIds();

        System.out.println("ThreadGroup: " + activeCount + " active thread(s)");
        System.out.println("Thread: " + stackTraces.size() + " stack trace(s) returned");
        System.out.println("ThreadMXBean: " + threadCount + " live threads(s)");
        System.out.println("ThreadMXBean: " + threadIds.length + " thread Id(s)");

        // check results are consistent
        boolean failed = false;
        if (activeCount != stackTraces.size()) failed = true;
        if (activeCount != threadCount) failed = true;
        if (activeCount != threadIds.length) failed = true;

        if (failed) {
            throw new RuntimeException("inconsistent results");
        }
    }
 
Example 10
Source File: ServerStatus.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public ServerStatus() {
  OperatingSystemMXBean operatingSystemMXBean =
    java.lang.management.ManagementFactory.getOperatingSystemMXBean();
  ThreadMXBean threadMXBean = java.lang.management.ManagementFactory.getThreadMXBean();
  RuntimeMXBean runtimeMXBean = java.lang.management.ManagementFactory.getRuntimeMXBean();

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

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

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

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

  long uptime = runtimeMXBean.getUptime();

  setCpuCores( cores );
  setCpuProcessTime( allThreadsCpuTime );
  setUptime( uptime );
  setThreadCount( threadCount );
  setLoadAvg( loadAvg );
  setOsName( osName );
  setOsVersion( osVersion );
  setOsArchitecture( osArch );
  setMemoryFree( freeMemory );
  setMemoryTotal( totalMemory );
}
 
Example 11
Source File: ServerStatus.java    From hop with Apache License 2.0 5 votes vote down vote up
public ServerStatus() {
  OperatingSystemMXBean operatingSystemMXBean =
    java.lang.management.ManagementFactory.getOperatingSystemMXBean();
  ThreadMXBean threadMXBean = java.lang.management.ManagementFactory.getThreadMXBean();
  RuntimeMXBean runtimeMXBean = java.lang.management.ManagementFactory.getRuntimeMXBean();

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

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

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

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

  long uptime = runtimeMXBean.getUptime();

  setCpuCores( cores );
  setCpuProcessTime( allThreadsCpuTime );
  setUptime( uptime );
  setThreadCount( threadCount );
  setLoadAvg( loadAvg );
  setOsName( osName );
  setOsVersion( osVersion );
  setOsArchitecture( osArch );
  setMemoryFree( freeMemory );
  setMemoryTotal( totalMemory );
}
 
Example 12
Source File: HotThreadsMonitor.java    From ns4_gear_watchdog with Apache License 2.0 5 votes vote down vote up
/**
 * Return the current hot threads information as provided by the JVM
 *
 * @param options Map of options to narrow this method functionality:
 *                Keys: ordered_by - can be "cpu", "wait" or "block"
 *                stacktrace_size - max depth of stack trace
 * @return A list of ThreadReport including all selected threads
 */
public static List<ThreadReport> detect(Map<String, String> options) {
    String type = "cpu";
    if (options.containsKey(ORDERED_BY)) {
        type = options.get(ORDERED_BY);
        if (!isValidSortOrder(type)) {
            throw new IllegalArgumentException("Invalid sort order");
        }
    }

    Integer threadInfoMaxDepth = 3;
    if (options.containsKey(STACKTRACE_SIZE)) {
        threadInfoMaxDepth = Integer.valueOf(options.get(STACKTRACE_SIZE));
    }

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    enableCpuTime(threadMXBean);

    Map<Long, ThreadReport> reports = new HashMap<>();

    for (long threadId : threadMXBean.getAllThreadIds()) {
        if (Thread.currentThread().getId() == threadId) {
            continue;
        }

        long cpuTime = threadMXBean.getThreadCpuTime(threadId);
        if (cpuTime == -1) {
            continue;
        }
        ThreadInfo info = threadMXBean.getThreadInfo(threadId, threadInfoMaxDepth);
        if (info != null) {
            /*
             * Thread ID must exist and be alive, otherwise the threads just
             * died in the meanwhile and could be ignored.
             */
            reports.put(threadId, new ThreadReport(info, cpuTime));
        }
    }
    return sort(new ArrayList<>(reports.values()), type);
}
 
Example 13
Source File: ThreadDumpTest.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 主方法
 */
public static void main(String[] args) throws Exception {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    long[] ids = threadMXBean.getAllThreadIds();
    ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(ids);
    for (ThreadInfo info : threadInfo) {
        System.out.println(info.getThreadId() + "\t" + info.getThreadState() + "\t" + info.getThreadName()+"\t");
    }
}
 
Example 14
Source File: MXBeanInteropTest1.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private final int doThreadMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- ThreadMXBean") ;

    try {
        ObjectName threadName =
                new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(threadName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t" + mbInfo);
        ThreadMXBean thread = null ;

        thread =
                JMX.newMXBeanProxy(mbsc,
                threadName,
                ThreadMXBean.class) ;
        System.out.println("findMonitorDeadlockedThreads\t\t"
                + thread.findMonitorDeadlockedThreads());
        long[] threadIDs = thread.getAllThreadIds() ;
        System.out.println("getAllThreadIds\t\t"
                + threadIDs);

        for ( long threadID : threadIDs ) {
            System.out.println("getThreadInfo long\t\t"
                    + thread.getThreadInfo(threadID));
            System.out.println("getThreadInfo long, int\t\t"
                    + thread.getThreadInfo(threadID, 2));
        }

        System.out.println("getThreadInfo long[]\t\t"
                + thread.getThreadInfo(threadIDs));
        System.out.println("getThreadInfo long[], int\t\t"
                + thread.getThreadInfo(threadIDs, 2));
        System.out.println("getDaemonThreadCount\t\t"
                + thread.getDaemonThreadCount());
        System.out.println("getPeakThreadCount\t\t"
                + thread.getPeakThreadCount());
        System.out.println("getThreadCount\t\t"
                + thread.getThreadCount());
        System.out.println("getTotalStartedThreadCount\t\t"
                + thread.getTotalStartedThreadCount());
        boolean supported = thread.isThreadContentionMonitoringSupported() ;
        System.out.println("isThreadContentionMonitoringSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("isThreadContentionMonitoringEnabled\t\t"
                    + thread.isThreadContentionMonitoringEnabled());
        }

        supported = thread.isThreadCpuTimeSupported() ;
        System.out.println("isThreadCpuTimeSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("isThreadCpuTimeEnabled\t\t"
                    + thread.isThreadCpuTimeEnabled());

            for (long id : threadIDs) {
                System.out.println("getThreadCpuTime(" + id + ")\t\t"
                        + thread.getThreadCpuTime(id));
                System.out.println("getThreadUserTime(" + id + ")\t\t"
                        + thread.getThreadUserTime(id));
            }
        }

        supported = thread.isCurrentThreadCpuTimeSupported() ;
        System.out.println("isCurrentThreadCpuTimeSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("getCurrentThreadCpuTime\t\t"
                    + thread.getCurrentThreadCpuTime());
            System.out.println("getCurrentThreadUserTime\t\t"
                    + thread.getCurrentThreadUserTime());
        }

        thread.resetPeakThreadCount() ;

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

    return errorCount ;
}
 
Example 15
Source File: MXBeanInteropTest1.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private final int doThreadMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- ThreadMXBean") ;

    try {
        ObjectName threadName =
                new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(threadName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t" + mbInfo);
        ThreadMXBean thread = null ;

        thread =
                JMX.newMXBeanProxy(mbsc,
                threadName,
                ThreadMXBean.class) ;
        System.out.println("findMonitorDeadlockedThreads\t\t"
                + thread.findMonitorDeadlockedThreads());
        long[] threadIDs = thread.getAllThreadIds() ;
        System.out.println("getAllThreadIds\t\t"
                + threadIDs);

        for ( long threadID : threadIDs ) {
            System.out.println("getThreadInfo long\t\t"
                    + thread.getThreadInfo(threadID));
            System.out.println("getThreadInfo long, int\t\t"
                    + thread.getThreadInfo(threadID, 2));
        }

        System.out.println("getThreadInfo long[]\t\t"
                + thread.getThreadInfo(threadIDs));
        System.out.println("getThreadInfo long[], int\t\t"
                + thread.getThreadInfo(threadIDs, 2));
        System.out.println("getDaemonThreadCount\t\t"
                + thread.getDaemonThreadCount());
        System.out.println("getPeakThreadCount\t\t"
                + thread.getPeakThreadCount());
        System.out.println("getThreadCount\t\t"
                + thread.getThreadCount());
        System.out.println("getTotalStartedThreadCount\t\t"
                + thread.getTotalStartedThreadCount());
        boolean supported = thread.isThreadContentionMonitoringSupported() ;
        System.out.println("isThreadContentionMonitoringSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("isThreadContentionMonitoringEnabled\t\t"
                    + thread.isThreadContentionMonitoringEnabled());
        }

        supported = thread.isThreadCpuTimeSupported() ;
        System.out.println("isThreadCpuTimeSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("isThreadCpuTimeEnabled\t\t"
                    + thread.isThreadCpuTimeEnabled());

            for (long id : threadIDs) {
                System.out.println("getThreadCpuTime(" + id + ")\t\t"
                        + thread.getThreadCpuTime(id));
                System.out.println("getThreadUserTime(" + id + ")\t\t"
                        + thread.getThreadUserTime(id));
            }
        }

        supported = thread.isCurrentThreadCpuTimeSupported() ;
        System.out.println("isCurrentThreadCpuTimeSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("getCurrentThreadCpuTime\t\t"
                    + thread.getCurrentThreadCpuTime());
            System.out.println("getCurrentThreadUserTime\t\t"
                    + thread.getCurrentThreadUserTime());
        }

        thread.resetPeakThreadCount() ;

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

    return errorCount ;
}
 
Example 16
Source File: JvmMetrics.java    From big-c with Apache License 2.0 4 votes vote down vote up
private void doThreadUpdates() {
    ThreadMXBean threadMXBean =
            ManagementFactory.getThreadMXBean();
    long threadIds[] = 
            threadMXBean.getAllThreadIds();
    ThreadInfo[] threadInfos =
            threadMXBean.getThreadInfo(threadIds, 0);
    
    int threadsNew = 0;
    int threadsRunnable = 0;
    int threadsBlocked = 0;
    int threadsWaiting = 0;
    int threadsTimedWaiting = 0;
    int threadsTerminated = 0;
    
    for (ThreadInfo threadInfo : threadInfos) {
        // threadInfo is null if the thread is not alive or doesn't exist
        if (threadInfo == null) continue;
        Thread.State state = threadInfo.getThreadState();
        if (state == NEW) {
            threadsNew++;
        } 
        else if (state == RUNNABLE) {
            threadsRunnable++;
        }
        else if (state == BLOCKED) {
            threadsBlocked++;
        }
        else if (state == WAITING) {
            threadsWaiting++;
        } 
        else if (state == TIMED_WAITING) {
            threadsTimedWaiting++;
        }
        else if (state == TERMINATED) {
            threadsTerminated++;
        }
    }
    metrics.setMetric("threadsNew", threadsNew);
    metrics.setMetric("threadsRunnable", threadsRunnable);
    metrics.setMetric("threadsBlocked", threadsBlocked);
    metrics.setMetric("threadsWaiting", threadsWaiting);
    metrics.setMetric("threadsTimedWaiting", threadsTimedWaiting);
    metrics.setMetric("threadsTerminated", threadsTerminated);
}
 
Example 17
Source File: JvmMetrics.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private void doThreadUpdates() {
    ThreadMXBean threadMXBean =
            ManagementFactory.getThreadMXBean();
    long threadIds[] = 
            threadMXBean.getAllThreadIds();
    ThreadInfo[] threadInfos =
            threadMXBean.getThreadInfo(threadIds, 0);
    
    int threadsNew = 0;
    int threadsRunnable = 0;
    int threadsBlocked = 0;
    int threadsWaiting = 0;
    int threadsTimedWaiting = 0;
    int threadsTerminated = 0;
    
    for (ThreadInfo threadInfo : threadInfos) {
        // threadInfo is null if the thread is not alive or doesn't exist
        if (threadInfo == null) continue;
        Thread.State state = threadInfo.getThreadState();
        if (state == NEW) {
            threadsNew++;
        } 
        else if (state == RUNNABLE) {
            threadsRunnable++;
        }
        else if (state == BLOCKED) {
            threadsBlocked++;
        }
        else if (state == WAITING) {
            threadsWaiting++;
        } 
        else if (state == TIMED_WAITING) {
            threadsTimedWaiting++;
        }
        else if (state == TERMINATED) {
            threadsTerminated++;
        }
    }
    metrics.setMetric("threadsNew", threadsNew);
    metrics.setMetric("threadsRunnable", threadsRunnable);
    metrics.setMetric("threadsBlocked", threadsBlocked);
    metrics.setMetric("threadsWaiting", threadsWaiting);
    metrics.setMetric("threadsTimedWaiting", threadsTimedWaiting);
    metrics.setMetric("threadsTerminated", threadsTerminated);
}
 
Example 18
Source File: NativeProtocol.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void appendDeadlockStatusInformation(Session sess, String xOpen, StringBuilder errorBuf) {
    if (sess.getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_includeInnodbStatusInDeadlockExceptions).getValue() && xOpen != null
            && (xOpen.startsWith("40") || xOpen.startsWith("41")) && getStreamingData() == null) {

        try {
            NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "SHOW ENGINE INNODB STATUS"), false, 0);

            Resultset rs = readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));

            int colIndex = 0;
            Field f = null;
            for (int i = 0; i < rs.getColumnDefinition().getFields().length; i++) {
                f = rs.getColumnDefinition().getFields()[i];
                if ("Status".equals(f.getName())) {
                    colIndex = i;
                    break;
                }
            }

            ValueFactory<String> vf = new StringValueFactory(f.getEncoding());

            Row r;
            if ((r = rs.getRows().next()) != null) {
                errorBuf.append("\n\n").append(r.getValue(colIndex, vf));
            } else {
                errorBuf.append("\n\n").append(Messages.getString("MysqlIO.NoInnoDBStatusFound"));
            }
        } catch (IOException | CJException ex) {
            errorBuf.append("\n\n").append(Messages.getString("MysqlIO.InnoDBStatusFailed")).append("\n\n").append(Util.stackTraceToString(ex));
        }
    }

    if (sess.getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_includeThreadDumpInDeadlockExceptions).getValue()) {
        errorBuf.append("\n\n*** Java threads running at time of deadlock ***\n\n");

        ThreadMXBean threadMBean = ManagementFactory.getThreadMXBean();
        long[] threadIds = threadMBean.getAllThreadIds();

        ThreadInfo[] threads = threadMBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
        List<ThreadInfo> activeThreads = new ArrayList<>();

        for (ThreadInfo info : threads) {
            if (info != null) {
                activeThreads.add(info);
            }
        }

        for (ThreadInfo threadInfo : activeThreads) {
            // "Thread-60" daemon prio=1 tid=0x093569c0 nid=0x1b99 in Object.wait()

            errorBuf.append('"').append(threadInfo.getThreadName()).append("\" tid=").append(threadInfo.getThreadId()).append(" ")
                    .append(threadInfo.getThreadState());

            if (threadInfo.getLockName() != null) {
                errorBuf.append(" on lock=").append(threadInfo.getLockName());
            }
            if (threadInfo.isSuspended()) {
                errorBuf.append(" (suspended)");
            }
            if (threadInfo.isInNative()) {
                errorBuf.append(" (running in native)");
            }

            StackTraceElement[] stackTrace = threadInfo.getStackTrace();

            if (stackTrace.length > 0) {
                errorBuf.append(" in ");
                errorBuf.append(stackTrace[0].getClassName()).append(".");
                errorBuf.append(stackTrace[0].getMethodName()).append("()");
            }

            errorBuf.append("\n");

            if (threadInfo.getLockOwnerName() != null) {
                errorBuf.append("\t owned by ").append(threadInfo.getLockOwnerName()).append(" Id=").append(threadInfo.getLockOwnerId()).append("\n");
            }

            for (int j = 0; j < stackTrace.length; j++) {
                StackTraceElement ste = stackTrace[j];
                errorBuf.append("\tat ").append(ste.toString()).append("\n");
            }
        }
    }
}
 
Example 19
Source File: MXBeanInteropTest1.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private final int doThreadMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- ThreadMXBean") ;

    try {
        ObjectName threadName =
                new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(threadName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t" + mbInfo);
        ThreadMXBean thread = null ;

        thread =
                JMX.newMXBeanProxy(mbsc,
                threadName,
                ThreadMXBean.class) ;
        System.out.println("findMonitorDeadlockedThreads\t\t"
                + thread.findMonitorDeadlockedThreads());
        long[] threadIDs = thread.getAllThreadIds() ;
        System.out.println("getAllThreadIds\t\t"
                + threadIDs);

        for ( long threadID : threadIDs ) {
            System.out.println("getThreadInfo long\t\t"
                    + thread.getThreadInfo(threadID));
            System.out.println("getThreadInfo long, int\t\t"
                    + thread.getThreadInfo(threadID, 2));
        }

        System.out.println("getThreadInfo long[]\t\t"
                + thread.getThreadInfo(threadIDs));
        System.out.println("getThreadInfo long[], int\t\t"
                + thread.getThreadInfo(threadIDs, 2));
        System.out.println("getDaemonThreadCount\t\t"
                + thread.getDaemonThreadCount());
        System.out.println("getPeakThreadCount\t\t"
                + thread.getPeakThreadCount());
        System.out.println("getThreadCount\t\t"
                + thread.getThreadCount());
        System.out.println("getTotalStartedThreadCount\t\t"
                + thread.getTotalStartedThreadCount());
        boolean supported = thread.isThreadContentionMonitoringSupported() ;
        System.out.println("isThreadContentionMonitoringSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("isThreadContentionMonitoringEnabled\t\t"
                    + thread.isThreadContentionMonitoringEnabled());
        }

        supported = thread.isThreadCpuTimeSupported() ;
        System.out.println("isThreadCpuTimeSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("isThreadCpuTimeEnabled\t\t"
                    + thread.isThreadCpuTimeEnabled());

            for (long id : threadIDs) {
                System.out.println("getThreadCpuTime(" + id + ")\t\t"
                        + thread.getThreadCpuTime(id));
                System.out.println("getThreadUserTime(" + id + ")\t\t"
                        + thread.getThreadUserTime(id));
            }
        }

        supported = thread.isCurrentThreadCpuTimeSupported() ;
        System.out.println("isCurrentThreadCpuTimeSupported\t\t"
                + supported);

        if ( supported ) {
            System.out.println("getCurrentThreadCpuTime\t\t"
                    + thread.getCurrentThreadCpuTime());
            System.out.println("getCurrentThreadUserTime\t\t"
                    + thread.getCurrentThreadUserTime());
        }

        thread.resetPeakThreadCount() ;

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

    return errorCount ;
}
 
Example 20
Source File: JvmMetrics.java    From hadoop-gpu with Apache License 2.0 4 votes vote down vote up
private void doThreadUpdates() {
    ThreadMXBean threadMXBean =
            ManagementFactory.getThreadMXBean();
    long threadIds[] = 
            threadMXBean.getAllThreadIds();
    ThreadInfo[] threadInfos =
            threadMXBean.getThreadInfo(threadIds, 0);
    
    int threadsNew = 0;
    int threadsRunnable = 0;
    int threadsBlocked = 0;
    int threadsWaiting = 0;
    int threadsTimedWaiting = 0;
    int threadsTerminated = 0;
    
    for (ThreadInfo threadInfo : threadInfos) {
        // threadInfo is null if the thread is not alive or doesn't exist
        if (threadInfo == null) continue;
        Thread.State state = threadInfo.getThreadState();
        if (state == NEW) {
            threadsNew++;
        } 
        else if (state == RUNNABLE) {
            threadsRunnable++;
        }
        else if (state == BLOCKED) {
            threadsBlocked++;
        }
        else if (state == WAITING) {
            threadsWaiting++;
        } 
        else if (state == TIMED_WAITING) {
            threadsTimedWaiting++;
        }
        else if (state == TERMINATED) {
            threadsTerminated++;
        }
    }
    metrics.setMetric("threadsNew", threadsNew);
    metrics.setMetric("threadsRunnable", threadsRunnable);
    metrics.setMetric("threadsBlocked", threadsBlocked);
    metrics.setMetric("threadsWaiting", threadsWaiting);
    metrics.setMetric("threadsTimedWaiting", threadsTimedWaiting);
    metrics.setMetric("threadsTerminated", threadsTerminated);
}