Search in sources :

Example 51 with ThreadInfo

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

the class JvmMetrics method getThreadUsage.

private void getThreadUsage(MetricsRecordBuilder rb) {
    int threadsNew = 0;
    int threadsRunnable = 0;
    int threadsBlocked = 0;
    int threadsWaiting = 0;
    int threadsTimedWaiting = 0;
    int threadsTerminated = 0;
    long[] threadIds = threadMXBean.getAllThreadIds();
    for (ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadIds, 0)) {
        // race protection
        if (threadInfo == null)
            continue;
        switch(threadInfo.getThreadState()) {
            case NEW:
                threadsNew++;
                break;
            case RUNNABLE:
                threadsRunnable++;
                break;
            case BLOCKED:
                threadsBlocked++;
                break;
            case WAITING:
                threadsWaiting++;
                break;
            case TIMED_WAITING:
                threadsTimedWaiting++;
                break;
            case TERMINATED:
                threadsTerminated++;
                break;
        }
    }
    rb.addGauge(ThreadsNew, threadsNew).addGauge(ThreadsRunnable, threadsRunnable).addGauge(ThreadsBlocked, threadsBlocked).addGauge(ThreadsWaiting, threadsWaiting).addGauge(ThreadsTimedWaiting, threadsTimedWaiting).addGauge(ThreadsTerminated, threadsTerminated);
}
Also used : ThreadInfo(java.lang.management.ThreadInfo)

Example 52 with ThreadInfo

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

the class StackServlet method printThreadInfo.

/**
 * Print all of the thread's information and stack traces.
 *
 * @param stream the stream to
 * @param title a string title for the stack trace
 */
private synchronized void printThreadInfo(PrintStream stream, String title) {
    final int STACK_DEPTH = 20;
    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();
}
Also used : ThreadInfo(java.lang.management.ThreadInfo)

Example 53 with ThreadInfo

use of java.lang.management.ThreadInfo in project elastic-core-maven by OrdinaryDude.

the class GetStackTraces method processRequest.

/**
 * Process the GetStackTraces API request
 *
 * @param   req                 API request
 * @return                      API response
 */
@Override
protected JSONStreamAware processRequest(HttpServletRequest req) {
    String value;
    // 
    // Get the number of trace lines to return
    // 
    int depth;
    value = req.getParameter("depth");
    if (value != null)
        depth = Math.max(Integer.valueOf(value), 1);
    else
        depth = Integer.MAX_VALUE;
    // 
    // Get the thread information
    // 
    JSONArray threadsJSON = new JSONArray();
    JSONArray locksJSON = new JSONArray();
    ThreadMXBean tmxBean = ManagementFactory.getThreadMXBean();
    boolean tmxMI = tmxBean.isObjectMonitorUsageSupported();
    ThreadInfo[] tList = tmxBean.dumpAllThreads(tmxMI, false);
    // 
    for (ThreadInfo tInfo : tList) {
        JSONObject threadJSON = new JSONObject();
        // 
        // General thread information
        // 
        threadJSON.put("id", tInfo.getThreadId());
        threadJSON.put("name", tInfo.getThreadName());
        threadJSON.put("state", tInfo.getThreadState().toString());
        // 
        if (tmxMI) {
            MonitorInfo[] mList = tInfo.getLockedMonitors();
            if (mList.length > 0) {
                JSONArray monitorsJSON = new JSONArray();
                for (MonitorInfo mInfo : mList) {
                    JSONObject lockJSON = new JSONObject();
                    lockJSON.put("name", mInfo.getClassName());
                    lockJSON.put("hash", mInfo.getIdentityHashCode());
                    lockJSON.put("depth", mInfo.getLockedStackDepth());
                    lockJSON.put("trace", mInfo.getLockedStackFrame().toString());
                    monitorsJSON.add(lockJSON);
                }
                threadJSON.put("locks", monitorsJSON);
            }
            if (tInfo.getThreadState() == Thread.State.BLOCKED) {
                LockInfo lInfo = tInfo.getLockInfo();
                if (lInfo != null) {
                    JSONObject lockJSON = new JSONObject();
                    lockJSON.put("name", lInfo.getClassName());
                    lockJSON.put("hash", lInfo.getIdentityHashCode());
                    lockJSON.put("thread", tInfo.getLockOwnerId());
                    threadJSON.put("blocked", lockJSON);
                    boolean addLock = true;
                    for (Object lock : locksJSON) {
                        if (((JSONObject) lock).get("name").equals(lInfo.getClassName())) {
                            addLock = false;
                            break;
                        }
                    }
                    if (addLock)
                        locksJSON.add(lockJSON);
                }
            }
        }
        // 
        // Add the stack trace
        // 
        StackTraceElement[] elements = tInfo.getStackTrace();
        JSONArray traceJSON = new JSONArray();
        int ix = 0;
        for (StackTraceElement element : elements) {
            traceJSON.add(element.toString());
            if (++ix == depth)
                break;
        }
        threadJSON.put("trace", traceJSON);
        // 
        // Add the thread to the response
        // 
        threadsJSON.add(threadJSON);
    }
    // 
    // Return the response
    // 
    JSONObject response = new JSONObject();
    response.put("threads", threadsJSON);
    response.put("locks", locksJSON);
    return response;
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) MonitorInfo(java.lang.management.MonitorInfo) JSONArray(org.json.simple.JSONArray) ThreadInfo(java.lang.management.ThreadInfo) JSONObject(org.json.simple.JSONObject) LockInfo(java.lang.management.LockInfo) JSONObject(org.json.simple.JSONObject)

Example 54 with ThreadInfo

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

the class Assembler method destroyResource.

private void destroyResource(final String name, final String className, final Object inObject) {
    Object object;
    try {
        object = LazyResource.class.isInstance(inObject) && LazyResource.class.cast(inObject).isInitialized() ? LazyResource.class.cast(inObject).getObject() : inObject;
    } catch (final NamingException e) {
        // in case it impl DestroyableResource
        object = inObject;
    }
    final Collection<Method> preDestroy = null;
    if (resourceDestroyTimeout != null) {
        final Duration d = new Duration(resourceDestroyTimeout);
        final ExecutorService es = Executors.newSingleThreadExecutor(new DaemonThreadFactory("openejb-resource-destruction-" + name));
        final Object o = object;
        try {
            es.submit(new Runnable() {

                @Override
                public void run() {
                    doResourceDestruction(name, className, o);
                }
            }).get(d.getTime(), d.getUnit());
        } catch (final InterruptedException e) {
            Thread.interrupted();
        } catch (final ExecutionException e) {
            throw RuntimeException.class.cast(e.getCause());
        } catch (final TimeoutException e) {
            logger.error("Can't destroy " + name + " in " + resourceDestroyTimeout + ", giving up.", e);
            if (threadStackOnTimeout) {
                final ThreadInfo[] dump = ManagementFactory.getThreadMXBean().dumpAllThreads(false, false);
                final ByteArrayOutputStream writer = new ByteArrayOutputStream();
                final PrintStream stream = new PrintStream(writer);
                for (final ThreadInfo info : dump) {
                    stream.println('"' + info.getThreadName() + "\" suspended=" + info.isSuspended() + " state=" + info.getThreadState());
                    for (final StackTraceElement traceElement : info.getStackTrace()) {
                        stream.println("\tat " + traceElement);
                    }
                }
                logger.info("Dump on " + name + " destruction timeout:\n" + new String(writer.toByteArray()));
            }
        }
    } else {
        doResourceDestruction(name, className, object);
    }
    callPreDestroy(name, object);
    removeResourceInfo(name);
}
Also used : PrintStream(java.io.PrintStream) DaemonThreadFactory(org.apache.openejb.util.DaemonThreadFactory) Duration(org.apache.openejb.util.Duration) Method(java.lang.reflect.Method) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) ThreadInfo(java.lang.management.ThreadInfo) ExecutorService(java.util.concurrent.ExecutorService) NamingException(javax.naming.NamingException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 55 with ThreadInfo

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

the class IgniteUtils method dumpThreads.

/**
 * Performs thread dump and prints all available info to the given log.
 *
 * @param log Logger.
 */
public static void dumpThreads(@Nullable IgniteLogger log) {
    ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
    final Set<Long> deadlockedThreadsIds = getDeadlockedThreadIds(mxBean);
    if (deadlockedThreadsIds.size() == 0)
        warn(log, "No deadlocked threads detected.");
    else
        warn(log, "Deadlocked threads detected (see thread dump below) " + "[deadlockedThreadsCnt=" + deadlockedThreadsIds.size() + ']');
    ThreadInfo[] threadInfos = mxBean.dumpAllThreads(mxBean.isObjectMonitorUsageSupported(), mxBean.isSynchronizerUsageSupported());
    GridStringBuilder sb = new GridStringBuilder("Thread dump at ").a(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z").format(new Date(U.currentTimeMillis()))).a(NL);
    for (ThreadInfo info : threadInfos) {
        printThreadInfo(info, sb, deadlockedThreadsIds);
        sb.a(NL);
        if (info.getLockedSynchronizers() != null && info.getLockedSynchronizers().length > 0) {
            printSynchronizersInfo(info.getLockedSynchronizers(), sb);
            sb.a(NL);
        }
    }
    sb.a(NL);
    warn(log, sb.toString());
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) ThreadInfo(java.lang.management.ThreadInfo) AtomicLong(java.util.concurrent.atomic.AtomicLong) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

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