Search in sources :

Example 31 with ThreadInfo

use of java.lang.management.ThreadInfo in project karaf by apache.

the class ThreadsAction method execute.

@Override
public Object execute() throws Exception {
    Map<Long, ThreadInfo> threadInfos = new TreeMap<>();
    ThreadMXBean threadsBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] infos;
    if (threadsBean.isObjectMonitorUsageSupported() && threadsBean.isSynchronizerUsageSupported()) {
        infos = threadsBean.dumpAllThreads(true, true);
    } else {
        infos = threadsBean.getThreadInfo(threadsBean.getAllThreadIds(), Integer.MAX_VALUE);
    }
    for (ThreadInfo info : infos) {
        threadInfos.put(info.getThreadId(), info);
    }
    if (id != null) {
        ThreadInfo ti = threadInfos.get(id);
        if (ti != null) {
            System.out.println("Thread " + ti.getThreadId() + " " + ti.getThreadName() + " " + ti.getThreadState());
            System.out.println("Stacktrace:");
            StackTraceElement[] st = ti.getStackTrace();
            for (StackTraceElement ste : st) {
                System.out.println(ste.getClassName() + "." + ste.getMethodName() + " line: " + ste.getLineNumber());
            }
        }
    } else if (list) {
        ShellTable table = new ShellTable();
        table.column("Id");
        table.column("Name");
        table.column("State");
        table.column("CPU time");
        table.column("Usr time");
        for (ThreadInfo thread : threadInfos.values()) {
            long id = thread.getThreadId();
            table.addRow().addContent(id, thread.getThreadName(), thread.getThreadState(), threadsBean.getThreadCpuTime(id) / 1000000, threadsBean.getThreadUserTime(id) / 1000000);
        }
        table.print(System.out, !noFormat);
    } else {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        while (group.getParent() != null) {
            group = group.getParent();
        }
        ThreadGroupData data = new ThreadGroupData(group, threadInfos);
        data.print();
    }
    return null;
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) ThreadInfo(java.lang.management.ThreadInfo) ShellTable(org.apache.karaf.shell.support.table.ShellTable) TreeMap(java.util.TreeMap)

Example 32 with ThreadInfo

use of java.lang.management.ThreadInfo in project jena by apache.

the class ConcurrencyTest method doTestConcurrency.

private void doTestConcurrency(final OntModel model) throws InterruptedException {
    // initialize the model
    final String NS = PrintUtil.egNS;
    model.enterCriticalSection(Lock.WRITE);
    final OntClass Top = model.createClass(NS + "Top");
    for (int i = 0; i < MODEL_SIZE; i++) {
        OntClass C = model.createClass(NS + "C" + i);
        Top.addSubClass(C);
        model.createIndividual(NS + "i" + i, C);
    }
    model.leaveCriticalSection();
    class QueryExecutingRunnable implements Runnable {

        @Override
        @SuppressWarnings("unchecked")
        public void run() {
            // Keep this thread running until the specified duration has expired
            long runStartedAt = System.currentTimeMillis();
            while (System.currentTimeMillis() - runStartedAt < TEST_LENGTH) {
                Thread.yield();
                model.enterCriticalSection(Lock.READ);
                try {
                    // Iterate over all statements
                    StmtIterator it = model.listStatements();
                    while (it.hasNext()) it.nextStatement();
                    it.close();
                    // Check number of instances of Top class
                    int count = 0;
                    ExtendedIterator<OntResource> ei = (ExtendedIterator<OntResource>) Top.listInstances();
                    while (ei.hasNext()) {
                        ei.next();
                        count++;
                    }
                    ei.close();
                    if (MODEL_SIZE != count) {
                        if (FULL_TEST)
                            System.err.println("Failure - found " + count + " instance, expected " + MODEL_SIZE);
                        throw new JenaException("Failure - found " + count + " instance, expected " + MODEL_SIZE);
                    }
                } finally {
                    model.leaveCriticalSection();
                }
            }
        }
    }
    // Start the threads
    ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
    for (int i = 0; i < NUM_THREADS; ++i) {
        executorService.submit(new QueryExecutingRunnable());
    }
    // Wait for threads to finish
    // this will *not* terminate any threads currently running
    executorService.shutdown();
    Thread.sleep(TEST_LENGTH + 50);
    // Possibly in deadlock, wait a little longer to be sure
    for (int i = 0; i < 50 && !executorService.isTerminated(); i++) {
        Thread.sleep(20);
    }
    if (!executorService.isTerminated()) {
        /* uncomment this block to perform deadlock checking, only on java 1.6 */
        // Check for deadlock
        ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
        long[] ids = tmx.findDeadlockedThreads();
        if (ids != null) {
            ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);
            System.err.println("*** Deadlocked threads");
            for (ThreadInfo ti : infos) {
                System.err.println("Thread \"" + ti.getThreadName() + "\" id=" + ti.getThreadId() + " " + ti.getThreadState().toString());
                System.err.println("Lock name: " + ti.getLockName() + " owned by \"" + ti.getLockOwnerName() + "\" id=" + ti.getLockOwnerId());
                System.err.println("\nStack trace:");
                for (StackTraceElement st : ti.getStackTrace()) System.err.println("   " + st.getClassName() + "." + st.getMethodName() + " (" + st.getFileName() + ":" + st.getLineNumber() + ")");
                System.err.println();
            }
        }
        Assert.assertTrue("Deadlock detected!", false);
        /* end deadlock block */
        assertTrue("Failed to terminate execution", false);
    }
}
Also used : StmtIterator(org.apache.jena.rdf.model.StmtIterator) ThreadMXBean(java.lang.management.ThreadMXBean) OntResource(org.apache.jena.ontology.OntResource) JenaException(org.apache.jena.shared.JenaException) ThreadInfo(java.lang.management.ThreadInfo) ExtendedIterator(org.apache.jena.util.iterator.ExtendedIterator) ExecutorService(java.util.concurrent.ExecutorService) OntClass(org.apache.jena.ontology.OntClass)

Example 33 with ThreadInfo

use of java.lang.management.ThreadInfo in project wildfly by wildfly.

the class AppClientStateSingleton method awaitAppClientCall.

@Override
public String awaitAppClientCall() {
    try {
        boolean b = latch.await(30, TimeUnit.SECONDS);
        logger.trace("Await returned: " + b + " : " + value);
        if (!b) {
            ThreadInfo[] threadInfos = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
            for (ThreadInfo info : threadInfos) {
                logger.trace(info);
            }
        }
        return value;
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : ThreadInfo(java.lang.management.ThreadInfo)

Example 34 with ThreadInfo

use of java.lang.management.ThreadInfo in project sling by apache.

the class ThreadUsageHealthCheck method collectThreadTimeInfos.

List<ThreadTimeInfo> collectThreadTimeInfos(FormattingResultLog log, ThreadMXBean threadMxBean) {
    Map<Long, ThreadTimeInfo> threadTimeInfos = new HashMap<Long, ThreadTimeInfo>();
    long[] allThreadIds = threadMxBean.getAllThreadIds();
    for (long threadId : allThreadIds) {
        ThreadTimeInfo threadTimeInfo = new ThreadTimeInfo();
        long threadCpuTimeStart = threadMxBean.getThreadCpuTime(threadId);
        threadTimeInfo.start = threadCpuTimeStart;
        ThreadInfo threadInfo = threadMxBean.getThreadInfo(threadId);
        threadTimeInfo.name = threadInfo != null ? threadInfo.getThreadName() : "Thread id " + threadId + " (name not resolvable)";
        threadTimeInfos.put(threadId, threadTimeInfo);
    }
    try {
        Thread.sleep(samplePeriodInMs);
    } catch (InterruptedException e) {
        log.warn("Could not sleep configured samplePeriodInMs={} to gather thread load", samplePeriodInMs);
    }
    for (long threadId : allThreadIds) {
        ThreadTimeInfo threadTimeInfo = threadTimeInfos.get(threadId);
        if (threadTimeInfo == null) {
            continue;
        }
        long threadCpuTimeStop = threadMxBean.getThreadCpuTime(threadId);
        threadTimeInfo.stop = threadCpuTimeStop;
    }
    List<ThreadTimeInfo> threads = new ArrayList<ThreadTimeInfo>(threadTimeInfos.values());
    return threads;
}
Also used : ThreadInfo(java.lang.management.ThreadInfo) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList)

Example 35 with ThreadInfo

use of java.lang.management.ThreadInfo in project asterixdb by apache.

the class ThreadDumpHelper method takeDumpJSON.

public static String takeDumpJSON(ThreadMXBean threadMXBean) throws IOException {
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    List<Map<String, Object>> threads = new ArrayList<>();
    for (ThreadInfo thread : threadInfos) {
        Map<String, Object> threadMap = new HashMap<>();
        threadMap.put("name", thread.getThreadName());
        threadMap.put("id", thread.getThreadId());
        threadMap.put("state", thread.getThreadState().name());
        List<String> stacktrace = new ArrayList<>();
        for (StackTraceElement element : thread.getStackTrace()) {
            stacktrace.add(element.toString());
        }
        threadMap.put("stack", stacktrace);
        if (thread.getLockName() != null) {
            threadMap.put("lock_name", thread.getLockName());
        }
        if (thread.getLockOwnerId() != -1) {
            threadMap.put("lock_owner_id", thread.getLockOwnerId());
        }
        if (thread.getBlockedTime() > 0) {
            threadMap.put("blocked_time", thread.getBlockedTime());
        }
        if (thread.getBlockedCount() > 0) {
            threadMap.put("blocked_count", thread.getBlockedCount());
        }
        if (thread.getLockedMonitors().length > 0) {
            threadMap.put("locked_monitors", thread.getLockedMonitors());
        }
        if (thread.getLockedSynchronizers().length > 0) {
            threadMap.put("locked_synchronizers", thread.getLockedSynchronizers());
        }
        threads.add(threadMap);
    }
    ObjectMapper om = new ObjectMapper();
    ObjectNode json = om.createObjectNode();
    json.put("date", new Date().toString());
    json.putPOJO("threads", threads);
    long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
    long[] monitorDeadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
    if (deadlockedThreads != null && deadlockedThreads.length > 0) {
        json.putPOJO("deadlocked_thread_ids", deadlockedThreads);
    }
    if (monitorDeadlockedThreads != null && monitorDeadlockedThreads.length > 0) {
        json.putPOJO("monitor_deadlocked_thread_ids", monitorDeadlockedThreads);
    }
    om.enable(SerializationFeature.INDENT_OUTPUT);
    return om.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Date(java.util.Date) ThreadInfo(java.lang.management.ThreadInfo) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

ThreadInfo (java.lang.management.ThreadInfo)124 ThreadMXBean (java.lang.management.ThreadMXBean)56 HashMap (java.util.HashMap)10 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8 HashSet (java.util.HashSet)7 Map (java.util.Map)7 LockInfo (java.lang.management.LockInfo)6 MonitorInfo (java.lang.management.MonitorInfo)6 Test (org.junit.Test)5 Date (java.util.Date)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 FileOutputStream (java.io.FileOutputStream)3 PrintStream (java.io.PrintStream)3 PrintWriter (java.io.PrintWriter)3 Method (java.lang.reflect.Method)3 LinkedHashSet (java.util.LinkedHashSet)3 TreeMap (java.util.TreeMap)3 ExecutorService (java.util.concurrent.ExecutorService)3 HealthCheckResultEntry (fish.payara.notification.healthcheck.HealthCheckResultEntry)2