Example usage for java.lang.management ThreadMXBean dumpAllThreads

List of usage examples for java.lang.management ThreadMXBean dumpAllThreads

Introduction

In this page you can find the example usage for java.lang.management ThreadMXBean dumpAllThreads.

Prototype

public ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers);

Source Link

Document

Returns the thread info for all live threads with stack trace and synchronization information.

Usage

From source file:Main.java

/**
 * //from ww w.j a va2 s  .  co m
 */
public static ThreadInfo[] getStackTraces() {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    return bean.dumpAllThreads(true, true);
}

From source file:Main.java

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());
        }//from www.  ja  v a2  s  . c o  m
        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);
}

From source file:Main.java

/** Returns all stack traces, including lock info. */
public static String getAllStackTraces() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    boolean monitor = threadMXBean.isObjectMonitorUsageSupported();
    boolean sync = threadMXBean.isSynchronizerUsageSupported();
    ThreadInfo[] allThreadInfo = threadMXBean.dumpAllThreads(monitor, sync);
    StringBuilder sb = new StringBuilder("Stack Trace Report:\n");
    buildTrace(allThreadInfo, sb);//  w w  w . j  a  v a2 s  .co m
    return sb.toString();
}

From source file:com.workplacesystems.utilsj.ThreadDumperJdk16.java

@Override
ThreadInfo[] getThreadInfos(ThreadMXBean bean) {
    return bean.dumpAllThreads(bean.isObjectMonitorUsageSupported(), bean.isSynchronizerUsageSupported());
}

From source file:com.francetelecom.clara.cloud.presentation.ExceptionViewFactory.java

public ExceptionView newView(Exception e) {
    Throwable rootCause = (ExceptionUtils.getRootCause(e) != null ? ExceptionUtils.getRootCause(e) : e);
    if (rootCause instanceof AuthorizationException) {
        return webPageFactory.getAuthorizationExceptionPage();
    }//from  www  .jav a 2  s  . co  m
    if (rootCause instanceof InvalidApplicationException) {
        return webPageFactory.getInvalidApplicationExceptionPage();
    }
    if (rootCause instanceof InvalidReleaseException) {
        return webPageFactory.getInvalidReleaseExceptionPage();
    }
    if (rootCause instanceof ObjectNotFoundException) {
        return webPageFactory.getObjectNotFoundExceptionPage();
    }
    if (rootCause instanceof WicketRuntimeException && rootCause.getMessage() != null
            && rootCause.getMessage().contains("Pagemap null is still locked")) {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        logger.debug("dumping threads for page map issue");
        logger.debug(threadMXBean.dumpAllThreads(true, true).toString());
        return webPageFactory.getUnknownExceptionPage();
    }

    return webPageFactory.getUnknownExceptionPage();
}

From source file:models.monitor.MonitorProvider.java

public ThreadInfo[] getThreadDump() {
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    return threadMxBean.dumpAllThreads(true, true);
}

From source file:com.streamsets.datacollector.restapi.AdminResource.java

@GET
@Path("/threads")
@ApiOperation(value = "Returns Thread Dump along with stack trace", response = Map.class, responseContainer = "List", authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)//from ww  w . j a  v a 2  s. co  m
@RolesAllowed({ AuthzRole.ADMIN, AuthzRole.ADMIN_REMOTE })
public Response getThreadsDump() throws IOException {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true);
    List<Map> augmented = new ArrayList<>(threads.length);
    for (ThreadInfo thread : threads) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("threadInfo", thread);
        map.put("userTimeNanosecs", threadMXBean.getThreadUserTime(thread.getThreadId()));
        map.put("cpuTimeNanosecs", threadMXBean.getThreadCpuTime(thread.getThreadId()));
        augmented.add(map);
    }
    return Response.ok(augmented).build();
}

From source file:org.opendaylight.controller.config.threadpool.fixed.FixedThreadPoolConfigBeanTest.java

private int countThreadsByPrefix(String prefix) {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    int result = 0;
    List<String> names = new ArrayList<>();
    for (ThreadInfo threadInfo : threadMXBean.dumpAllThreads(false, false)) {
        names.add(threadInfo.getThreadName());
        if (threadInfo.getThreadName().startsWith(prefix)) {
            result++;//from  ww w  . ja v a  2s .  c om
        }
    }
    LOG.info("Current threads {}", names);
    return result;
}

From source file:com.thoughtworks.go.server.service.support.ThreadInformationProvider.java

private TreeMap<Long, Map<String, Object>> getStackTraceInformation(ThreadMXBean threadMXBean) {
    TreeMap<Long, Map<String, Object>> traces = new TreeMap<>();
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    for (ThreadInfo threadInfo : threadInfos) {
        LinkedHashMap<String, Object> threadStackTrace = new LinkedHashMap<>();
        threadStackTrace.put("Id", threadInfo.getThreadId());
        threadStackTrace.put("Name", threadInfo.getThreadName());
        threadStackTrace.put("State", threadInfo.getThreadState());

        LinkedHashMap<String, Object> lockMonitorInfo = new LinkedHashMap<>();
        MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors();
        ArrayList<Map<String, Object>> lockedMonitorsJson = new ArrayList<>();

        for (MonitorInfo lockedMonitor : lockedMonitors) {
            LinkedHashMap<String, Object> lockedMonitorJson = new LinkedHashMap<>();
            lockedMonitorJson.put("Class", lockedMonitor.getClassName());
            lockedMonitorJson.put("IdentityHashCode", lockedMonitor.getIdentityHashCode());
            lockedMonitorJson.put("LockedStackDepth", lockedMonitor.getLockedStackDepth());
            lockedMonitorJson.put("StackFrame", lockedMonitor.getLockedStackFrame().toString());
            lockedMonitorsJson.add(lockedMonitorJson);
        }/*from   w w  w.  j ava 2 s . co m*/

        lockMonitorInfo.put("Locked Monitors", lockedMonitorsJson);
        lockMonitorInfo.put("Locked Synchronizers", asJSON(threadInfo.getLockedSynchronizers()));
        threadStackTrace.put("Lock Monitor Info", lockMonitorInfo);

        LinkedHashMap<String, Object> blockedInfo = new LinkedHashMap<>();
        blockedInfo.put("Blocked Time", threadInfo.getBlockedTime() == -1 ? null : threadInfo.getBlockedTime());
        blockedInfo.put("Blocked Count", threadInfo.getBlockedCount());
        threadStackTrace.put("Blocked Info", blockedInfo);

        LinkedHashMap<String, Object> timeInfo = new LinkedHashMap<>();
        timeInfo.put("Waited Time", threadInfo.getWaitedTime() == -1 ? null : threadInfo.getWaitedTime());
        timeInfo.put("Waited Count", threadInfo.getWaitedCount());
        threadStackTrace.put("Time Info", timeInfo);

        LinkedHashMap<String, Object> lockInfoMap = new LinkedHashMap<>();
        LockInfo lockInfo = threadInfo.getLockInfo();
        lockInfoMap.put("Locked On", asJSON(lockInfo));
        lockInfoMap.put("Lock Owner Thread Id",
                threadInfo.getLockOwnerId() == -1 ? null : threadInfo.getLockOwnerId());
        lockInfoMap.put("Lock Owner Thread Name", threadInfo.getLockOwnerName());
        threadStackTrace.put("Lock Info", lockInfoMap);

        LinkedHashMap<String, Object> stateInfo = new LinkedHashMap<>();
        stateInfo.put("Suspended", threadInfo.isSuspended());
        stateInfo.put("InNative", threadInfo.isInNative());
        threadStackTrace.put("State Info", stateInfo);

        threadStackTrace.put("Stack Trace", asJSON(threadInfo.getStackTrace()));
        traces.put(threadInfo.getThreadId(), threadStackTrace);
    }
    return traces;
}

From source file:com.streamsets.datacollector.bundles.content.SdcInfoContentGenerator.java

public void threadDump(BundleWriter writer) throws IOException {
    writer.markStartOfFile("runtime/threads.txt");

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true);

    // Sadly we can't easily do info.toString() as the implementation is hardcoded to cut the stack trace only to 8
    // items which does not serve our purpose well. Hence we have custom implementation that prints entire stack trace
    // for all threads.
    for (ThreadInfo info : threads) {
        StringBuilder sb = new StringBuilder(
                "\"" + info.getThreadName() + "\"" + " Id=" + info.getThreadId() + " " + info.getThreadState());
        if (info.getLockName() != null) {
            sb.append(" on " + info.getLockName());
        }//from  ww w .ja va  2s  .  c  o m
        if (info.getLockOwnerName() != null) {
            sb.append(" owned by \"" + info.getLockOwnerName() + "\" Id=" + info.getLockOwnerId());
        }
        if (info.isSuspended()) {
            sb.append(" (suspended)");
        }
        if (info.isInNative()) {
            sb.append(" (in native)");
        }
        sb.append('\n');
        int i = 0;
        for (StackTraceElement ste : info.getStackTrace()) {
            if (i == 0 && info.getLockInfo() != null) {
                Thread.State ts = info.getThreadState();
                switch (ts) {
                case BLOCKED:
                    sb.append("\t-  blocked on " + info.getLockInfo());
                    sb.append('\n');
                    break;
                case WAITING:
                    sb.append("\t-  waiting on " + info.getLockInfo());
                    sb.append('\n');
                    break;
                case TIMED_WAITING:
                    sb.append("\t-  waiting on " + info.getLockInfo());
                    sb.append('\n');
                    break;
                default:
                }
            }
            sb.append("\tat " + ste.toString());
            sb.append('\n');

            i++;

            for (MonitorInfo mi : info.getLockedMonitors()) {
                if (mi.getLockedStackDepth() == i) {
                    sb.append("\t-  locked " + mi);
                    sb.append('\n');
                }
            }
        }

        LockInfo[] locks = info.getLockedSynchronizers();
        if (locks.length > 0) {
            sb.append("\n\tNumber of locked synchronizers = " + locks.length);
            sb.append('\n');
            for (LockInfo li : locks) {
                sb.append("\t- " + li);
                sb.append('\n');
            }
        }
        sb.append('\n');

        writer.write(sb.toString());
    }

    writer.markEndOfFile();
}