Search in sources :

Example 61 with ThreadMXBean

use of java.lang.management.ThreadMXBean in project jdk8u_jdk by JetBrains.

the class JvmThreadInstanceEntryImpl method getJvmThreadInstWaitTimeMs.

/**
     * Getter for the "JvmThreadInstWaitTimeMs" variable.
     */
public Long getJvmThreadInstWaitTimeMs() throws SnmpStatusException {
    long l = 0;
    final ThreadMXBean tmb = JvmThreadingImpl.getThreadMXBean();
    if (tmb.isThreadContentionMonitoringSupported()) {
        l = info.getWaitedTime();
        //Monitoring is disabled
        if (l == -1)
            l = 0;
    }
    return new Long(l);
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean)

Example 62 with ThreadMXBean

use of java.lang.management.ThreadMXBean in project jvm-tools by aragozin.

the class CaptureCheck method capture.

@Test
public void capture() throws FileNotFoundException, IOException {
    File dump = new File(taget);
    if (dump.getParentFile() != null) {
        dump.getParentFile().mkdirs();
    }
    UniversalEventWriter writer = ThreadEventCodec.createEventWriter(new FileOutputStream(dump));
    MyEventWriter twriter = TypedEventWriterProxy.decorate(writer).pass(ThreadSnapshotEvent.class).pass(GarbageCollectionEvent.class).facade(MyEventWriter.class);
    MBeanServerConnection conn = AttachManager.getJmxConnection(PID);
    GcEventSubscriber subscriber = new GcEventSubscriber(conn, new SimpleGcEventEncoder(twriter));
    if (!subscriber.subscribe()) {
        // polling fallback
        subscriber.schedule(500);
    }
    ThreadDumpSampler tdumper = new ThreadDumpSampler();
    ThreadMXBean threadMXBean = ThreadMXBeanEx.BeanHelper.connectThreadMXBean(conn);
    if (threadMXBean.isThreadContentionMonitoringSupported()) {
        threadMXBean.setThreadContentionMonitoringEnabled(true);
    }
    tdumper.connect(threadMXBean);
    long deadline = System.currentTimeMillis() + captureTime;
    ThreadEventAdapter threadWriter = new ThreadEventAdapter(twriter);
    while (System.currentTimeMillis() < deadline) {
        tdumper.collect(threadWriter);
    }
    twriter.close();
    System.out.println("Dump complete [" + dump.getPath() + "] " + dump.length() + " bytes");
    int tc = 0;
    int ntc = 0;
    EventReader<Event> reader = ThreadEventCodec.createEventReader(new FileInputStream(dump));
    for (Event e : reader) {
        if (e instanceof ThreadSnapshotEvent) {
            ++tc;
        } else {
            ++ntc;
        }
    }
    System.out.println("Thread events: " + tc + " Non thread events: " + ntc);
}
Also used : SimpleGcEventEncoder(org.gridkit.jvmtool.gcmon.SimpleGcEventEncoder) ThreadMXBean(java.lang.management.ThreadMXBean) UniversalEventWriter(org.gridkit.jvmtool.event.UniversalEventWriter) FileInputStream(java.io.FileInputStream) GcEventSubscriber(org.gridkit.jvmtool.gcmon.GcEventSubscriber) ThreadSnapshotEvent(org.gridkit.jvmtool.codec.stacktrace.ThreadSnapshotEvent) FileOutputStream(java.io.FileOutputStream) GarbageCollectionEvent(org.gridkit.jvmtool.gcmon.GarbageCollectionEvent) ThreadSnapshotEvent(org.gridkit.jvmtool.codec.stacktrace.ThreadSnapshotEvent) Event(org.gridkit.jvmtool.event.Event) GarbageCollectionEvent(org.gridkit.jvmtool.gcmon.GarbageCollectionEvent) File(java.io.File) MBeanServerConnection(javax.management.MBeanServerConnection) ThreadDumpSampler(org.gridkit.jvmtool.stacktrace.ThreadDumpSampler) Test(org.junit.Test)

Example 63 with ThreadMXBean

use of java.lang.management.ThreadMXBean in project elasticsearch by elastic.

the class HotThreads method innerDetect.

private String innerDetect() throws Exception {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    if (threadBean.isThreadCpuTimeSupported() == false) {
        throw new ElasticsearchException("thread CPU time is not supported on this JDK");
    }
    StringBuilder sb = new StringBuilder();
    sb.append("Hot threads at ");
    sb.append(DATE_TIME_FORMATTER.printer().print(System.currentTimeMillis()));
    sb.append(", interval=");
    sb.append(interval);
    sb.append(", busiestThreads=");
    sb.append(busiestThreads);
    sb.append(", ignoreIdleThreads=");
    sb.append(ignoreIdleThreads);
    sb.append(":\n");
    Map<Long, MyThreadInfo> threadInfos = new HashMap<>();
    for (long threadId : threadBean.getAllThreadIds()) {
        // ignore our own thread...
        if (Thread.currentThread().getId() == threadId) {
            continue;
        }
        long cpu = threadBean.getThreadCpuTime(threadId);
        if (cpu == -1) {
            continue;
        }
        ThreadInfo info = threadBean.getThreadInfo(threadId, 0);
        if (info == null) {
            continue;
        }
        threadInfos.put(threadId, new MyThreadInfo(cpu, info));
    }
    Thread.sleep(interval.millis());
    for (long threadId : threadBean.getAllThreadIds()) {
        // ignore our own thread...
        if (Thread.currentThread().getId() == threadId) {
            continue;
        }
        long cpu = threadBean.getThreadCpuTime(threadId);
        if (cpu == -1) {
            threadInfos.remove(threadId);
            continue;
        }
        ThreadInfo info = threadBean.getThreadInfo(threadId, 0);
        if (info == null) {
            threadInfos.remove(threadId);
            continue;
        }
        MyThreadInfo data = threadInfos.get(threadId);
        if (data != null) {
            data.setDelta(cpu, info);
        } else {
            threadInfos.remove(threadId);
        }
    }
    // sort by delta CPU time on thread.
    List<MyThreadInfo> hotties = new ArrayList<>(threadInfos.values());
    final int busiestThreads = Math.min(this.busiestThreads, hotties.size());
    // skip that for now
    CollectionUtil.introSort(hotties, new Comparator<MyThreadInfo>() {

        @Override
        public int compare(MyThreadInfo o1, MyThreadInfo o2) {
            if ("cpu".equals(type)) {
                return (int) (o2.cpuTime - o1.cpuTime);
            } else if ("wait".equals(type)) {
                return (int) (o2.waitedTime - o1.waitedTime);
            } else if ("block".equals(type)) {
                return (int) (o2.blockedTime - o1.blockedTime);
            }
            throw new IllegalArgumentException("expected thread type to be either 'cpu', 'wait', or 'block', but was " + type);
        }
    });
    // analyse N stack traces for M busiest threads
    long[] ids = new long[busiestThreads];
    for (int i = 0; i < busiestThreads; i++) {
        MyThreadInfo info = hotties.get(i);
        ids[i] = info.info.getThreadId();
    }
    ThreadInfo[][] allInfos = new ThreadInfo[threadElementsSnapshotCount][];
    for (int j = 0; j < threadElementsSnapshotCount; j++) {
        // NOTE, javadoc of getThreadInfo says: If a thread of the given ID is not alive or does not exist,
        // null will be set in the corresponding element in the returned array. A thread is alive if it has
        // been started and has not yet died.
        allInfos[j] = threadBean.getThreadInfo(ids, Integer.MAX_VALUE);
        Thread.sleep(threadElementsSnapshotDelay.millis());
    }
    for (int t = 0; t < busiestThreads; t++) {
        long time = 0;
        if ("cpu".equals(type)) {
            time = hotties.get(t).cpuTime;
        } else if ("wait".equals(type)) {
            time = hotties.get(t).waitedTime;
        } else if ("block".equals(type)) {
            time = hotties.get(t).blockedTime;
        }
        String threadName = null;
        for (ThreadInfo[] info : allInfos) {
            if (info != null && info[t] != null) {
                if (ignoreIdleThreads && isIdleThread(info[t])) {
                    info[t] = null;
                    continue;
                }
                threadName = info[t].getThreadName();
                break;
            }
        }
        if (threadName == null) {
            // thread is not alive yet or died before the first snapshot - ignore it!
            continue;
        }
        double percent = (((double) time) / interval.nanos()) * 100;
        sb.append(String.format(Locale.ROOT, "%n%4.1f%% (%s out of %s) %s usage by thread '%s'%n", percent, TimeValue.timeValueNanos(time), interval, type, threadName));
        // for each snapshot (2nd array index) find later snapshot for same thread with max number of
        // identical StackTraceElements (starting from end of each)
        boolean[] done = new boolean[threadElementsSnapshotCount];
        for (int i = 0; i < threadElementsSnapshotCount; i++) {
            if (done[i])
                continue;
            int maxSim = 1;
            boolean[] similars = new boolean[threadElementsSnapshotCount];
            for (int j = i + 1; j < threadElementsSnapshotCount; j++) {
                if (done[j])
                    continue;
                int similarity = similarity(allInfos[i][t], allInfos[j][t]);
                if (similarity > maxSim) {
                    maxSim = similarity;
                    similars = new boolean[threadElementsSnapshotCount];
                }
                if (similarity == maxSim)
                    similars[j] = true;
            }
            // print out trace maxSim levels of i, and mark similar ones as done
            int count = 1;
            for (int j = i + 1; j < threadElementsSnapshotCount; j++) {
                if (similars[j]) {
                    done[j] = true;
                    count++;
                }
            }
            if (allInfos[i][t] != null) {
                final StackTraceElement[] show = allInfos[i][t].getStackTrace();
                if (count == 1) {
                    sb.append(String.format(Locale.ROOT, "  unique snapshot%n"));
                    for (int l = 0; l < show.length; l++) {
                        sb.append(String.format(Locale.ROOT, "    %s%n", show[l]));
                    }
                } else {
                    sb.append(String.format(Locale.ROOT, "  %d/%d snapshots sharing following %d elements%n", count, threadElementsSnapshotCount, maxSim));
                    for (int l = show.length - maxSim; l < show.length; l++) {
                        sb.append(String.format(Locale.ROOT, "    %s%n", show[l]));
                    }
                }
            }
        }
    }
    return sb.toString();
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ElasticsearchException(org.elasticsearch.ElasticsearchException) ThreadInfo(java.lang.management.ThreadInfo)

Example 64 with ThreadMXBean

use of java.lang.management.ThreadMXBean in project hazelcast by hazelcast.

the class TimedMemberStateFactoryHelper method createRuntimeProps.

static void createRuntimeProps(MemberStateImpl memberState) {
    Runtime runtime = Runtime.getRuntime();
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    ClassLoadingMXBean clMxBean = ManagementFactory.getClassLoadingMXBean();
    MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemory = memoryMxBean.getHeapMemoryUsage();
    MemoryUsage nonHeapMemory = memoryMxBean.getNonHeapMemoryUsage();
    Map<String, Long> map = new HashMap<String, Long>();
    map.put("runtime.availableProcessors", Integer.valueOf(runtime.availableProcessors()).longValue());
    map.put("date.startTime", runtimeMxBean.getStartTime());
    map.put("seconds.upTime", runtimeMxBean.getUptime());
    map.put("memory.maxMemory", runtime.maxMemory());
    map.put("memory.freeMemory", runtime.freeMemory());
    map.put("memory.totalMemory", runtime.totalMemory());
    map.put("memory.heapMemoryMax", heapMemory.getMax());
    map.put("memory.heapMemoryUsed", heapMemory.getUsed());
    map.put("memory.nonHeapMemoryMax", nonHeapMemory.getMax());
    map.put("memory.nonHeapMemoryUsed", nonHeapMemory.getUsed());
    map.put("runtime.totalLoadedClassCount", clMxBean.getTotalLoadedClassCount());
    map.put("runtime.loadedClassCount", Integer.valueOf(clMxBean.getLoadedClassCount()).longValue());
    map.put("runtime.unloadedClassCount", clMxBean.getUnloadedClassCount());
    map.put("runtime.totalStartedThreadCount", threadMxBean.getTotalStartedThreadCount());
    map.put("runtime.threadCount", Integer.valueOf(threadMxBean.getThreadCount()).longValue());
    map.put("runtime.peakThreadCount", Integer.valueOf(threadMxBean.getPeakThreadCount()).longValue());
    map.put("runtime.daemonThreadCount", Integer.valueOf(threadMxBean.getDaemonThreadCount()).longValue());
    OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
    map.put("osMemory.freePhysicalMemory", get(osMxBean, "getFreePhysicalMemorySize", 0L));
    map.put("osMemory.committedVirtualMemory", get(osMxBean, "getCommittedVirtualMemorySize", 0L));
    map.put("osMemory.totalPhysicalMemory", get(osMxBean, "getTotalPhysicalMemorySize", 0L));
    map.put("osSwap.freeSwapSpace", get(osMxBean, "getFreeSwapSpaceSize", 0L));
    map.put("osSwap.totalSwapSpace", get(osMxBean, "getTotalSwapSpaceSize", 0L));
    map.put("os.maxFileDescriptorCount", get(osMxBean, "getMaxFileDescriptorCount", 0L));
    map.put("os.openFileDescriptorCount", get(osMxBean, "getOpenFileDescriptorCount", 0L));
    map.put("os.processCpuLoad", get(osMxBean, "getProcessCpuLoad", -1L));
    map.put("os.systemLoadAverage", get(osMxBean, "getSystemLoadAverage", -1L));
    map.put("os.systemCpuLoad", get(osMxBean, "getSystemCpuLoad", -1L));
    map.put("os.processCpuTime", get(osMxBean, "getProcessCpuTime", 0L));
    map.put("os.availableProcessors", get(osMxBean, "getAvailableProcessors", 0L));
    memberState.setRuntimeProps(map);
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) MemoryMXBean(java.lang.management.MemoryMXBean) HashMap(java.util.HashMap) ClassLoadingMXBean(java.lang.management.ClassLoadingMXBean) RuntimeMXBean(java.lang.management.RuntimeMXBean) MemoryUsage(java.lang.management.MemoryUsage) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean)

Example 65 with ThreadMXBean

use of java.lang.management.ThreadMXBean in project cassandra by apache.

the class ToolsTester method setupTester.

@BeforeClass
public static void setupTester() {
    System.setProperty("cassandra.partitioner", "org.apache.cassandra.dht.Murmur3Partitioner");
    // may start an async appender
    LoggerFactory.getLogger(ToolsTester.class);
    ThreadMXBean threads = ManagementFactory.getThreadMXBean();
    initialThreads = Arrays.asList(threads.getThreadInfo(threads.getAllThreadIds()));
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) BeforeClass(org.junit.BeforeClass)

Aggregations

ThreadMXBean (java.lang.management.ThreadMXBean)105 ThreadInfo (java.lang.management.ThreadInfo)56 HashMap (java.util.HashMap)9 RuntimeMXBean (java.lang.management.RuntimeMXBean)8 MemoryMXBean (java.lang.management.MemoryMXBean)7 IOException (java.io.IOException)6 OperatingSystemMXBean (java.lang.management.OperatingSystemMXBean)6 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 File (java.io.File)5 HashSet (java.util.HashSet)5 Test (org.junit.Test)5 ClassLoadingMXBean (java.lang.management.ClassLoadingMXBean)4 GarbageCollectorMXBean (java.lang.management.GarbageCollectorMXBean)4 MemoryUsage (java.lang.management.MemoryUsage)4 HealthCheckResultEntry (fish.payara.notification.healthcheck.HealthCheckResultEntry)3 HealthCheckResult (fish.payara.nucleus.healthcheck.HealthCheckResult)3 LockInfo (java.lang.management.LockInfo)3 ManagementFactory (java.lang.management.ManagementFactory)3 MonitorInfo (java.lang.management.MonitorInfo)3