Example usage for java.lang Thread getId

List of usage examples for java.lang Thread getId

Introduction

In this page you can find the example usage for java.lang Thread getId.

Prototype

public long getId() 

Source Link

Document

Returns the identifier of this Thread.

Usage

From source file:com.nubits.nubot.utils.Utils.java

public static void logActiveThreads() {
    int active = Thread.activeCount();
    LOG.trace("currently active threads: " + active);
    Thread allThreads[] = new Thread[active];
    Thread.enumerate(allThreads);

    for (int i = 0; i < active; i++) {
        Thread t = allThreads[i];
        LOG.trace(i + ": " + t + " id: " + t.getId() + " name: " + t.getName() + " " + t.getContextClassLoader()
                + " group: " + t.getThreadGroup() + " alive" + t.isAlive());
        LOG.trace("super: " + t.getClass().getSuperclass());
    }//from   w  w  w  . ja  va  2 s .c  o  m

    if (active > maxThreadsError) {
        LOG.error("too many threads started");
    }
}

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//from  w w w.  j a  va2s . 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.opennms.core.test.db.TemporaryDatabase.java

public static void dumpThreads() {
    Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
    int daemons = 0;
    for (Thread t : threads.keySet()) {
        if (t.isDaemon()) {
            daemons++;//from w w w .  j  a  v  a  2  s  . c  o  m
        }
    }
    System.err.println("Thread dump of " + threads.size() + " threads (" + daemons + " daemons):");
    Map<Thread, StackTraceElement[]> sortedThreads = new TreeMap<Thread, StackTraceElement[]>(
            new Comparator<Thread>() {
                public int compare(final Thread t1, final Thread t2) {
                    return Long.valueOf(t1.getId()).compareTo(Long.valueOf(t2.getId()));
                }
            });
    sortedThreads.putAll(threads);

    for (Entry<Thread, StackTraceElement[]> entry : sortedThreads.entrySet()) {
        Thread thread = entry.getKey();
        System.err.println("Thread " + thread.getId() + (thread.isDaemon() ? " (daemon)" : "") + ": " + thread
                + " (state: " + thread.getState() + ")");
        for (StackTraceElement e : entry.getValue()) {
            System.err.println("\t" + e);
        }
    }
    System.err.println("Thread dump completed.");
}

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  w ww  .ja  va 2 s.  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();/*from   w  w w. j  a  v  a  2 s. co  m*/
        }
        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();
    }
}

From source file:org.opennms.core.test.db.TemporaryDatabasePostgreSQL.java

public static void dumpThreads() {
    Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
    int daemons = 0;
    for (Thread t : threads.keySet()) {
        if (t.isDaemon()) {
            daemons++;// w ww  . jav  a 2s.c  o m
        }
    }
    System.err.println("Thread dump of " + threads.size() + " threads (" + daemons + " daemons):");
    Map<Thread, StackTraceElement[]> sortedThreads = new TreeMap<Thread, StackTraceElement[]>(
            new Comparator<Thread>() {
                @Override
                public int compare(final Thread t1, final Thread t2) {
                    return Long.valueOf(t1.getId()).compareTo(Long.valueOf(t2.getId()));
                }
            });
    sortedThreads.putAll(threads);

    for (Entry<Thread, StackTraceElement[]> entry : sortedThreads.entrySet()) {
        Thread thread = entry.getKey();
        System.err.println("Thread " + thread.getId() + (thread.isDaemon() ? " (daemon)" : "") + ": " + thread
                + " (state: " + thread.getState() + ")");
        for (StackTraceElement e : entry.getValue()) {
            System.err.println("\t" + e);
        }
    }
    System.err.println("Thread dump completed.");
}

From source file:cc.osint.graphd.processes.InboundChannelProcess.java

public void log(String s) {
    try {// w w w.  jav  a 2s .c  o  m
        Thread t = Thread.currentThread();
        System.out.println(t.getId() + ": " + clientId + ": InboundChannelProcess: " + s);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.l2jfree.lang.L2Thread.java

public static List<String> getStats() {
    List<String> list = new FastList<String>();

    list.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").format(new Date()));
    list.add("");
    list.add("## Java Platform Information ##");
    list.add("Java Runtime Name: " + System.getProperty("java.runtime.name"));
    list.add("Java Version: " + System.getProperty("java.version"));
    list.add("Java Class Version: " + System.getProperty("java.class.version"));
    list.add("");
    list.add("## Virtual Machine Information ##");
    list.add("VM Name: " + System.getProperty("java.vm.name"));
    list.add("VM Version: " + System.getProperty("java.vm.version"));
    list.add("VM Vendor: " + System.getProperty("java.vm.vendor"));
    list.add("VM Info: " + System.getProperty("java.vm.info"));
    list.add("");
    list.add("## OS Information ##");
    list.add("Name: " + System.getProperty("os.name"));
    list.add("Architeture: " + System.getProperty("os.arch"));
    list.add("Version: " + System.getProperty("os.version"));
    list.add("");
    list.add("## Runtime Information ##");
    list.add("CPU Count: " + Runtime.getRuntime().availableProcessors());
    list.add("");
    for (String line : getMemoryUsageStatistics())
        list.add(line);/* ww w  . ja  va 2  s .co  m*/
    list.add("");
    list.add("## Class Path Information ##\n");
    for (String lib : System.getProperty("java.class.path").split(File.pathSeparator))
        if (!list.contains(lib))
            list.add(lib);
    list.add("");

    Set<Thread> threads = new TreeSet<Thread>(new Comparator<Thread>() {
        @Override
        public int compare(Thread t1, Thread t2) {
            if (t1.isDaemon() != t2.isDaemon())
                return Boolean.valueOf(t1.isDaemon()).compareTo(t2.isDaemon());

            final StackTraceElement[] st1 = t1.getStackTrace();
            final StackTraceElement[] st2 = t2.getStackTrace();

            for (int i = 1;; i++) {
                final int i1 = st1.length - i;
                final int i2 = st2.length - i;

                if (i1 < 0 || i2 < 0)
                    break;

                final int compare = st1[i1].toString().compareToIgnoreCase(st2[i2].toString());

                if (compare != 0)
                    return compare;
            }

            if (st1.length != st2.length)
                return Integer.valueOf(st1.length).compareTo(st2.length);

            return Long.valueOf(t1.getId()).compareTo(t2.getId());
        }
    });
    threads.addAll(Thread.getAllStackTraces().keySet());
    list.add("## " + threads.size() + " thread(s) ##");
    list.add("=================================================");

    int i = 1;
    for (Thread thread : threads) {
        list.add("");
        list.add(i++ + ".");
        list.addAll(getStats(thread));
    }

    return list;
}

From source file:com.l2jfree.gameserver.threadmanager.DeadlockDetector.java

private Thread findThreadById(long id) {
    for (Thread thread : Thread.getAllStackTraces().keySet())
        if (thread.getId() == id)
            return thread;

    throw new IllegalStateException("Deadlocked Thread not found!");
}

From source file:cc.osint.graphd.sim.GraphProcess.java

public void log(String s) {
    try {/*from   ww  w  .j a v  a  2s  . c  om*/
        Thread t = Thread.currentThread();
        System.out.println(t.getId() + ": " + name + ": " + s);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}