List of usage examples for java.lang Thread getAllStackTraces
public static Map<Thread, StackTraceElement[]> getAllStackTraces()
From source file:org.b3log.symphony.util.Markdowns.java
/** * Converts the specified markdown text to HTML. * * @param markdownText the specified markdown text * @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns * 'markdownErrorLabel' if exception// w ww . j av a2 s .c om */ public static String toHTML(final String markdownText) { if (Strings.isEmptyOrNull(markdownText)) { return ""; } final String cachedHTML = getHTML(markdownText); if (null != cachedHTML) { return cachedHTML; } final ExecutorService pool = Executors.newSingleThreadExecutor(); final long[] threadId = new long[1]; final Callable<String> call = () -> { threadId[0] = Thread.currentThread().getId(); String html = LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); if (MARKED_AVAILABLE) { html = toHtmlByMarked(markdownText); if (!StringUtils.startsWith(html, "<p>")) { html = "<p>" + html + "</p>"; } } else { com.vladsch.flexmark.ast.Node document = PARSER.parse(markdownText); html = RENDERER.render(document); if (!StringUtils.startsWith(html, "<p>")) { html = "<p>" + html + "</p>"; } } final Document doc = Jsoup.parse(html); final List<org.jsoup.nodes.Node> toRemove = new ArrayList<>(); doc.traverse(new NodeVisitor() { @Override public void head(final org.jsoup.nodes.Node node, int depth) { if (node instanceof org.jsoup.nodes.TextNode) { final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node; final org.jsoup.nodes.Node parent = textNode.parent(); if (parent instanceof Element) { final Element parentElem = (Element) parent; if (!parentElem.tagName().equals("code")) { String text = textNode.getWholeText(); boolean nextIsBr = false; final org.jsoup.nodes.Node nextSibling = textNode.nextSibling(); if (nextSibling instanceof Element) { nextIsBr = "br".equalsIgnoreCase(((Element) nextSibling).tagName()); } if (null != userQueryService) { try { final Set<String> userNames = userQueryService.getUserNames(text); for (final String userName : userNames) { text = text.replace('@' + userName + (nextIsBr ? "" : " "), "@<a href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a> "); } text = text.replace("@participants ", "@<a href='https://hacpai.com/article/1458053458339' class='ft-red'>participants</a> "); } finally { JdbcRepository.dispose(); } } if (text.contains("@<a href=")) { final List<org.jsoup.nodes.Node> nodes = Parser.parseFragment(text, parentElem, ""); final int index = textNode.siblingIndex(); parentElem.insertChildren(index, nodes); toRemove.add(node); } else { textNode.text(Pangu.spacingText(text)); } } } } } @Override public void tail(org.jsoup.nodes.Node node, int depth) { } }); toRemove.forEach(node -> node.remove()); doc.select("pre>code").addClass("hljs"); doc.select("a").forEach(a -> { String src = a.attr("href"); if (!StringUtils.startsWithIgnoreCase(src, Latkes.getServePath())) { try { src = URLEncoder.encode(src, "UTF-8"); } catch (final Exception e) { } a.attr("href", Latkes.getServePath() + "/forward?goto=" + src); a.attr("target", "_blank"); } }); doc.outputSettings().prettyPrint(false); String ret = doc.select("body").html(); ret = StringUtils.trim(ret); // cache it putHTML(markdownText, ret); return ret; }; Stopwatchs.start("Md to HTML"); try { final Future<String> future = pool.submit(call); return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]"); Callstacks.printCallstack(Level.ERROR, new String[] { "org.b3log" }, null); final Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (final Thread thread : threads) { if (thread.getId() == threadId[0]) { thread.stop(); break; } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e); } finally { pool.shutdownNow(); Stopwatchs.end(); } return LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); }
From source file:org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.java
public void printActiveThreadsNumber() { List<String> threads = Thread.getAllStackTraces().keySet().stream() .filter(t -> t.getThreadGroup() == null || !t.getThreadGroup().getName().equals("system")) .filter(t -> t.getState() != Thread.State.TERMINATED).map(Thread::toString) .collect(Collectors.toList()); System.out.println("ActiveThreads: " + threads.size()); // threads.forEach(s -> System.out.println("\t" + s)); }
From source file:pcgen.util.Logging.java
/** * List the current stack of all threads to STDOUT. *///from w ww .j a v a 2 s .com public static void reportAllThreads() { Map<Thread, StackTraceElement[]> allThreads = Thread.getAllStackTraces(); StringBuilder b = new StringBuilder(); for (Thread t : allThreads.keySet()) { b.append("Thread: "); b.append(t.getName()); b.append(", stacktrace:\n"); StackTraceElement[] traces = allThreads.get(t); for (StackTraceElement element : traces) { b.append(" "); b.append(element.toString()); b.append('\n'); } } System.out.println("==== Thread listing ===="); System.out.println(b); System.out.println("===== end listing ====="); }
From source file:org.apache.jorphan.util.JOrphanUtils.java
/** * Display currently running threads on system.out * This may be expensive to run./*from w w w. j av a 2s .c om*/ * Mainly designed for use at the end of a non-GUI test to check for threads that might prevent the JVM from exiting. * * @param includeDaemons whether to include daemon threads or not. */ public static void displayThreads(boolean includeDaemons) { Map<Thread, StackTraceElement[]> m = Thread.getAllStackTraces(); String lineSeparator = System.getProperty("line.separator"); StringBuilder builder = new StringBuilder(); for (Map.Entry<Thread, StackTraceElement[]> e : m.entrySet()) { boolean daemon = e.getKey().isDaemon(); if (includeDaemons || !daemon) { builder.setLength(0); StackTraceElement[] ste = e.getValue(); for (StackTraceElement stackTraceElement : ste) { int lineNumber = stackTraceElement.getLineNumber(); builder.append(stackTraceElement.getClassName() + "#" + stackTraceElement.getMethodName() + (lineNumber >= 0 ? " at line:" + stackTraceElement.getLineNumber() : "") + lineSeparator); } System.out.println(e.getKey().toString() + ((daemon ? " (daemon)" : "")) + ", stackTrace:" + builder.toString()); } } }
From source file:org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.java
public void printActiveThreads() { System.out.println("========================================="); System.out.println("Thread.activeCount() = " + Thread.activeCount()); Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces(); Set<String> groups = allStackTraces.keySet().stream() .filter(t -> t.getThreadGroup() == null || !t.getThreadGroup().getName().equals("system")) .map(t -> String.valueOf(t.getThreadGroup())).collect(Collectors.toSet()); for (String group : groups) { System.out.println("group = " + group); for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) { Thread thread = entry.getKey(); if (String.valueOf(thread.getThreadGroup()).equals(group)) { System.out.println("\t[" + thread.getId() + "] " + thread.toString() + ":" + thread.getState()); }//from w ww. ja va2s. c om } } System.out.println("========================================="); }
From source file:com.spotify.helios.system.SystemTestBase.java
private void listThreads() { final Set<Thread> threads = Thread.getAllStackTraces().keySet(); final Map<String, Thread> sorted = Maps.newTreeMap(); for (final Thread t : threads) { final ThreadGroup tg = t.getThreadGroup(); if (t.isAlive() && (tg == null || !tg.getName().equals("system"))) { sorted.put(t.getName(), t);//from w ww . java 2 s. c o m } } log.info("= THREADS " + Strings.repeat("=", 70)); for (final Thread t : sorted.values()) { final ThreadGroup tg = t.getThreadGroup(); log.info("{}: \"{}\" ({}{})", t.getId(), t.getName(), (tg == null ? "" : tg.getName() + " "), (t.isDaemon() ? "daemon" : "")); } log.info(Strings.repeat("=", 80)); }
From source file:org.openmrs.util.OpenmrsClassLoader.java
public static void onShutdown() { //Since we are shutting down, stop all threads that reference the openmrs class loader. Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for (Thread thread : threadArray) { ClassLoader classLoader = thread.getContextClassLoader(); //Threads like Finalizer, Reference Handler, etc have null class loader reference. if (classLoader == null) { continue; }// w w w . j av a2s . co m if (classLoader instanceof OpenmrsClassLoader) { try { //Set to WebappClassLoader just in case stopping fails. thread.setContextClassLoader(classLoader.getParent()); //Stopping the current thread will halt all current cleanup. //So do not ever ever even attempt stopping it. :) if (thread == Thread.currentThread()) { continue; } log.info("onShutdown Stopping thread: " + thread.getName()); thread.stop(); } catch (Exception ex) { log.error(ex.getMessage(), ex); } } } clearReferences(); }
From source file:org.kuali.ole.sys.context.SpringContext.java
static void initMonitoringThread() { ConfigurationService configurationService = GlobalResourceLoader.getService("kualiConfigurationService"); if (configurationService.getPropertyValueAsBoolean("periodic.thread.dump")) { final long sleepPeriod = Long.parseLong( configurationService.getPropertyValueAsString("periodic.thread.dump.seconds")) * 1000; final File logDir = new File(configurationService.getPropertyValueAsString("logs.directory")); final File monitoringLogDir = new File(logDir, "monitoring"); if (!monitoringLogDir.exists()) { monitoringLogDir.mkdir();/*from ww w . java 2s.c om*/ } if (LOG.isInfoEnabled()) { LOG.info("Starting the Periodic Thread Dump thread - dumping every " + (sleepPeriod / 1000) + " seconds"); LOG.info("Periodic Thread Dump Logs: " + monitoringLogDir.getAbsolutePath()); } final DateFormat df = new SimpleDateFormat("yyyyMMdd"); final DateFormat tf = new SimpleDateFormat("HH-mm-ss"); Runnable processWatch = new Runnable() { @Override public void run() { while (true) { Date now = new Date(); File todaysLogDir = new File(monitoringLogDir, df.format(now)); if (!todaysLogDir.exists()) { todaysLogDir.mkdir(); } File logFile = new File(todaysLogDir, "process-" + tf.format(now) + ".log"); try { StringBuilder logStatement = new StringBuilder(10240); logStatement.append("Threads Running at: ").append(now).append("\n\n\n"); Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces(); List<Thread> sortedThreads = new ArrayList<Thread>(threads.keySet()); Collections.sort(sortedThreads, new Comparator<Thread>() { @Override public int compare(Thread o1, Thread o2) { return o1.getName().compareTo(o2.getName()); } }); for (Thread t : sortedThreads) { logStatement.append("\tThread: name=").append(t.getName()).append(", id=") .append(t.getId()).append(", priority=").append(t.getPriority()) .append(", state=").append(t.getState()); logStatement.append('\n'); for (StackTraceElement stackTraceElement : threads.get(t)) { logStatement.append("\t\t" + stackTraceElement).append('\n'); } logStatement.append('\n'); } FileUtils.writeStringToFile(logFile, logStatement.toString(), "UTF-8"); } catch (IOException ex) { LOG.error("Unable to write the ProcessWatch output file: " + logFile.getAbsolutePath(), ex); } try { Thread.sleep(sleepPeriod); } catch (InterruptedException ex) { LOG.error("woken up during sleep of the ProcessWatch thread", ex); } } } }; processWatchThread = new Thread(processWatch, "ProcessWatch thread"); processWatchThread.setDaemon(true); processWatchThread.start(); } }
From source file:org.kuali.kfs.sys.context.SpringContext.java
static void initMonitoringThread() { if (KRADServiceLocator.getKualiConfigurationService().getPropertyValueAsBoolean("periodic.thread.dump")) { final long sleepPeriod = Long.parseLong(KRADServiceLocator.getKualiConfigurationService() .getPropertyValueAsString("periodic.thread.dump.seconds")) * 1000; final File logDir = new File( KRADServiceLocator.getKualiConfigurationService().getPropertyValueAsString("logs.directory")); final File monitoringLogDir = new File(logDir, "monitoring"); if (!monitoringLogDir.exists()) { monitoringLogDir.mkdir();/* w w w . j av a 2s.c om*/ } if (LOG.isInfoEnabled()) { LOG.info("Starting the Periodic Thread Dump thread - dumping every " + (sleepPeriod / 1000) + " seconds"); LOG.info("Periodic Thread Dump Logs: " + monitoringLogDir.getAbsolutePath()); } final DateFormat df = new SimpleDateFormat("yyyyMMdd"); final DateFormat tf = new SimpleDateFormat("HH-mm-ss"); Runnable processWatch = new Runnable() { @Override public void run() { while (true) { Date now = new Date(); File todaysLogDir = new File(monitoringLogDir, df.format(now)); if (!todaysLogDir.exists()) { todaysLogDir.mkdir(); } File logFile = new File(todaysLogDir, "process-" + tf.format(now) + ".log"); try { createParentDirs(logFile); BufferedWriter w = new BufferedWriter(new FileWriter(logFile)); StringBuilder logStatement = new StringBuilder(10240); logStatement.append("Threads Running at: ").append(now).append("\n\n\n"); Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces(); List<Thread> sortedThreads = new ArrayList<Thread>(threads.keySet()); Collections.sort(sortedThreads, new Comparator<Thread>() { @Override public int compare(Thread o1, Thread o2) { return o1.getName().compareTo(o2.getName()); } }); for (Thread t : sortedThreads) { logStatement.append("\tThread: name=").append(t.getName()).append(", id=") .append(t.getId()).append(", priority=").append(t.getPriority()) .append(", state=").append(t.getState()); logStatement.append('\n'); for (StackTraceElement stackTraceElement : threads.get(t)) { logStatement.append("\t\t" + stackTraceElement).append('\n'); } logStatement.append('\n'); } w.write(logStatement.toString()); w.close(); } catch (IOException ex) { LOG.error("Unable to write the ProcessWatch output file: " + logFile.getAbsolutePath(), ex); } try { Thread.sleep(sleepPeriod); } catch (InterruptedException ex) { LOG.error("woken up during sleep of the ProcessWatch thread", ex); } } } }; processWatchThread = new Thread(processWatch, "ProcessWatch thread"); processWatchThread.setDaemon(true); processWatchThread.start(); } }