Get a formatted dump of all threads with associated state and stack traces.

@return a formatted dump of all threads with associated state and stack traces.
423548
public static String threadDump()
    {
        final StringBuilder sb = new StringBuilder();
        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        for (final ThreadInfo info : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), Integer.MAX_VALUE))
        {
            sb.append('"').append(info.getThreadName()).append("\": ").append(info.getThreadState());

            for (final StackTraceElement stackTraceElement : info.getStackTrace())
            {
                sb.append("\n    at ").append(stackTraceElement.toString());
            }

            sb.append("\n\n");
        }

        return sb.toString();
    }
949033
def dump_threads(stream=None):
    '''
    
    '''
    if stream is None:
        stream = sys.stderr
    thread_id_to_name = {}
    try:
        for t in threading.enumerate():
            thread_id_to_name[t.ident] = '%s  (daemon: %s, pydevd thread: %s)' % (
                t.name, t.daemon, getattr(t, 'is_pydev_daemon_thread', False))
    except:
        pass

    from _pydevd_bundle.pydevd_additional_thread_info_regular import _current_frames

    stream.write('===============================================================================\n')
    stream.write('Threads running\n')
    stream.write('================================= Thread Dump =================================\n')
    stream.flush()

    for thread_id, stack in _current_frames().items():
        stream.write('\n-------------------------------------------------------------------------------\n')
        stream.write(" Thread %s" % thread_id_to_name.get(thread_id, thread_id))
        stream.write('\n\n')

        for i, (filename, lineno, name, line) in enumerate(traceback.extract_stack(stack)):

            stream.write(' File "%s", line %d, in %s\n' % (filename, lineno, name))
            if line:
                stream.write("   %s\n" % (line.strip()))

            if i == 0 and 'self' in stack.f_locals:
                stream.write('   self: ')
                try:
                    stream.write(str(stack.f_locals['self']))
                except:
                    stream.write('Unable to get str of: %s' % (type(stack.f_locals['self']),))
                stream.write('\n')
        stream.flush()

    stream.write('\n=============================== END Thread Dump ===============================')
    stream.flush()
220492
private static void listAllThreads(final PrintWriter out) {
        final ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
        ThreadGroup rootThreadGroup = currentThreadGroup;
        ThreadGroup parent = rootThreadGroup.getParent();

        while (parent != null) {
            rootThreadGroup = parent;
            parent = parent.getParent();
        }

        // And list it, recursively
        Util.printGroupInfo(out, rootThreadGroup, "");
    }
624394
private String dumpQueuedThread(Thread t)
   {
      StringBuilder sb = new StringBuilder();

      // Header
      sb = sb.append("Queued thread: ");
      sb = sb.append(t.getName());
      sb = sb.append(newLine);

      // Body
      StackTraceElement[] stes = SecurityActions.getStackTrace(t);
      if (stes != null)
      {
         for (StackTraceElement ste : stes)
         {
            sb = sb.append("  ");
            sb = sb.append(ste.getClassName());
            sb = sb.append(":");
            sb = sb.append(ste.getMethodName());
            sb = sb.append(":");
            sb = sb.append(ste.getLineNumber());
            sb = sb.append(newLine);
         }
      }

      return sb.toString();
   }
449962
public Map<String, ThreadPoolStatus> getStatusOfThreadPools(){
		Map<String, ThreadPoolStatus> result = new TreeMap<String, ThreadPoolStatus>();
		for (Map.Entry<String, ? extends ThreadPoolExecutor> entry: threadPools.entrySet()){
			ThreadPoolStatus status = new ThreadPoolStatus();
			status.setName(entry.getKey());
			ThreadPoolExecutor pool = entry.getValue();
			status.setActive(pool.getActiveCount());
			status.setKeepAliveSeconds(pool.getKeepAliveTime(TimeUnit.SECONDS));
			status.setLargestSize(pool.getLargestPoolSize());
			status.setMaxSize(pool.getMaximumPoolSize());
			status.setSize(pool.getPoolSize());
			status.setQueueLength(pool.getQueue().size());
			result.put(entry.getKey(), status);
		}
		return result;
	}
96602
@GET
    @Path("stack")
    @Produces(MediaType.TEXT_PLAIN)
    public String getThreadDump() {
        if (LOG.isDebugEnabled()) {
            LOG.debug("==> AdminResource.getThreadDump()");
        }

        ThreadGroup topThreadGroup = Thread.currentThread().getThreadGroup();

        while (topThreadGroup.getParent() != null) {
            topThreadGroup = topThreadGroup.getParent();
        }
        Thread[] threads = new Thread[topThreadGroup.activeCount()];

        int nr = topThreadGroup.enumerate(threads);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < nr; i++) {
            builder.append(threads[i].getName()).append("\nState: ").
                    append(threads[i].getState()).append("\n");
            String stackTrace = StringUtils.join(threads[i].getStackTrace(), "\n");
            builder.append(stackTrace);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("<== AdminResource.getThreadDump()");
        }

        return builder.toString();
    }
1262426
private HttpLocalFormat getFormat() {
        HttpLocalFormat format = threadStorage.get();
        if (null == format) {
            format = new HttpLocalFormat();
            threadStorage.set(format);
        }
        return format;
    }
1234311
public String dumpCounters() {
    // CHECK IF STATISTICS ARE ACTIVED
    if (recording < 0)
      return "Counters: <no recording>";

    final StringBuilder buffer = new StringBuilder();

    synchronized (counters) {
      buffer.append("DUMPING COUNTERS (last reset on: " + lastReset.toString() + ")...");

      buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
      buffer.append(String.format("\n%50s | Value                                                             |", "Name"));
      buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));

      final List<String> keys = new ArrayList<String>(counters.keySet());
      Collections.sort(keys);

      for (String k : keys) {
        final Long stat = counters.get(k);
        buffer.append(String.format("\n%-50s | %-65d |", k, stat));
      }
    }

    buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
    return buffer.toString();
  }
435540
public double getCumulativeElapsedTimeAllCurrentThread() {
	  double sum = 0;
	  
	  Accumulator acc = getAccForThread();
	  if (acc == null) {
		  return sum;
	  }

      for (int i = 1; i <= ProfilingEvent.EXECUTED.ordinal(); ++i) {
         sum += acc.accumulatedTimes[i];
      }
      
      return sum;
   }
84457
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
        checkPermission(ADMINISTER);

        // issue the requests all at once
        Map<String,Future<Map<String,String>>> future = new HashMap<>();

        for (Computer c : getComputers()) {
            try {
                future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
            } catch(Exception e) {
                LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
            }
        }
        if (toComputer() == null) {
            future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
        }

        // if the result isn't available in 5 sec, ignore that.
        // this is a precaution against hang nodes
        long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(5);

        Map<String,Map<String,String>> r = new HashMap<>();
        for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
            try {
                r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
            } catch (Exception x) {
                r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump", Functions.printThrowable(x)));
            }
        }
        return Collections.unmodifiableSortedMap(new TreeMap<>(r));
    }
723923
public static String getTotalStackTrace( final Throwable    exception )
    {
        if( isBroadestFirst() )
        {
            StringWriter    writer = new StringWriter();
            exception.printStackTrace( new PrintWriter( writer, true ) );

            return writer.toString();
        }

        //
        //     Reverse the order of the exceptions
        //
        List<Throwable>    exceps = new ArrayList<Throwable>();
        Throwable    rev = exception;

        while ( rev != null && rev.getCause() != rev )
        {
            exceps.add( 0, rev );

            rev = rev.getCause();
        }

        StringBuffer   buffer = new StringBuffer();

        for ( int ii = 0; ii < exceps.size(); ii++ )
        {
            Throwable    ex = exceps.get( ii );
            Throwable    parent = null;
            if ( ii != 0 )
            {
                buffer.append( "\n\nIn context of:\n" );
                parent = exceps.get( ii -1 );
            }

            buffer.append( ex.toString() );
            StackTraceElement[]    trace = ex.getStackTrace();
            for ( int jj=0; jj < trace.length; jj++)
            {
                StackTraceElement    traceElement = trace[jj];

                boolean    done = false;
                if ( parent != null )
                {
                    StackTraceElement[]    parentTrace = parent.getStackTrace();
                    for ( int kk=0; kk < parentTrace.length; kk++ )
                    {
                        if ( parentTrace[kk].equals( traceElement ) )
                        {
                            done = true;
                            break;
                        }
                    }
                }

                buffer.append("\n\tat " + traceElement );

                if ( done )
                {
                    buffer.append( "\n\t..." );
                    break;
                }
            }
        }

        return buffer.toString();
    }
1074521
public int threads() {
    int threads = reader.getInteger(THREADS, DEFAULT_THREADS);
    if (threads == -1) {
      return Runtime.getRuntime().availableProcessors();
    }
    return threads;
  }
215103
private String dumpThreadInfo(Thread thread, StackTraceElement[] stackTrace, StringBuilder sb) {
		sb.append('\"').append(thread.getName()).append("\" Id=").append(thread.getId()).append(' ')
				.append(thread.getState());
		sb.append('\n');
		int i = 0;
		for (; i < Math.min(maxStackLevel, stackTrace.length); i++) {
			StackTraceElement ste = stackTrace[i];
			sb.append("\tat ").append(ste).append('\n');
		}
		if (i < stackTrace.length) {
			sb.append("\t...").append('\n');
		}

		sb.append('\n');
		return sb.toString();
	}
74835
public java.util.List<StackResourceSummary> getStackResourceSummaries() {
        if (stackResourceSummaries == null) {
            stackResourceSummaries = new com.amazonaws.internal.SdkInternalList<StackResourceSummary>();
        }
        return stackResourceSummaries;
    }
576664
public static String[] currentStack() {
    return Stream.of(Thread.currentThread().getStackTrace()).map(Object::toString).toArray(i -> new String[i]);
  }
1314670
public ArrayList getThreads()
  {
    if (tc.isEntryEnabled())
    {
      SibTr.entry(tc, "getThreads");
      SibTr.exit(tc, "getThreads", _threadCache);
    }
    return _threadCache;
  }
453735
def threads_list(io_handler, max_depth=1):
        
        # Normalize maximum depth
        try:
            max_depth = int(max_depth)
            if max_depth < 1:
                max_depth = None
        except (ValueError, TypeError):
            max_depth = None

        # pylint: disable=W0212
        try:
            # Extract frames
            frames = sys._current_frames()

            # Get the thread ID -> Thread mapping
            names = threading._active.copy()
        except AttributeError:
            io_handler.write_line("sys._current_frames() is not available.")
            return

        # Sort by thread ID
        thread_ids = sorted(frames.keys())
        lines = []
        for thread_id in thread_ids:
            # Get the corresponding stack
            stack = frames[thread_id]

            # Try to get the thread name
            try:
                name = names[thread_id].name
            except KeyError:
                name = "<unknown>"

            # Construct the code position
            lines.append("Thread ID: {0} - Name: {1}".format(thread_id, name))
            lines.append("Stack Trace:")

            trace_lines = []
            depth = 0
            frame = stack
            while frame is not None and (
                max_depth is None or depth < max_depth
            ):
                # Store the line information
                trace_lines.append(format_frame_info(frame))

                # Previous frame...
                frame = frame.f_back
                depth += 1

            # Reverse the lines
            trace_lines.reverse()

            # Add them to the printed lines
            lines.extend(trace_lines)
            lines.append("")

        lines.append("")

        # Sort the lines
        io_handler.write("\n".join(lines))