Example usage for java.lang Thread getState

List of usage examples for java.lang Thread getState

Introduction

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

Prototype

public State getState() 

Source Link

Document

Returns the state of this thread.

Usage

From source file:org.tranche.logs.LogUtil.java

/**
 * //from  w  ww .  j av a  2s. c o  m
 * @return
 */
public static final String getThreadDump() {
    Map<Thread, StackTraceElement[]> threadInfo = Thread.getAllStackTraces();
    StringBuffer buf = new StringBuffer();
    buf.append("Thread dump: " + threadInfo.size() + " threads");
    buf.append("\n" + "\n");
    for (Thread t : threadInfo.keySet()) {
        StackTraceElement[] ste = threadInfo.get(t);
        String daemonMsg = t.isDaemon() ? "daemon" : "non-daemon";
        String aliveMsg = t.isAlive() ? "alive" : "non-alive";
        buf.append("    * " + t.getName() + " (priority: " + t.getPriority() + ", " + daemonMsg + ", "
                + aliveMsg + ", state: " + t.getState() + ") ");
        buf.append("\n");

        for (int i = 0; i < ste.length; i++) {
            buf.append("        " + ste[i].toString());
            buf.append("\n");
        }

        buf.append("\n");
    }
    buf.append("\n" + "\n");
    return buf.toString();
}

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 ww  .  j ava  2 s. co  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.jboss.dashboard.profiler.ThreadProfile.java

public static String printStackTrace(Thread t, int lines) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    pw.println("'" + t.getName() + "' '" + t.getState().toString() + "' ");
    StackTraceElement[] trace = t.getStackTrace();
    for (int i = 0; i < trace.length && i < lines; i++) {
        pw.println("\tat " + trace[i]);
    }//from w w  w . ja va2 s. co  m
    return sw.toString();
}

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  w  w  .  j  av  a2 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 {
                        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 ww  . j a 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 {
                        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  w w.  j  av  a 2  s . co  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:org.apache.ambari.server.testing.DeadlockWarningThread.java

@Override
public void run() {
    while (true) {
        try {//from   w  w  w .  j  a  va 2 s. c om
            Thread.sleep(3000);
        } catch (InterruptedException ex) {
        }
        long[] ids = mbean.findMonitorDeadlockedThreads();
        StringBuilder errBuilder = new StringBuilder();
        if (ids != null && ids.length > 0) {
            errBuilder.append(getThreadsStacktraces(Arrays.asList(ArrayUtils.toObject(ids))));
            errorMessages.add(errBuilder.toString());
            System.out.append(errBuilder.toString());
            //Exit if deadlocks have been found         
            deadlocked = true;
            break;
        } else {
            //Exit if all monitored threads were finished
            boolean hasLive = false;
            boolean hasRunning = false;
            for (Thread monTh : monitoredThreads) {
                State state = monTh.getState();
                if (state != State.TERMINATED && state != State.NEW) {
                    hasLive = true;
                }
                if (state == State.RUNNABLE || state == State.TIMED_WAITING) {
                    hasRunning = true;
                    break;
                }
            }

            if (!hasLive) {
                deadlocked = false;
                break;
            } else if (!hasRunning) {
                List<Long> tIds = new ArrayList<Long>();
                for (Thread monitoredThread : monitoredThreads) {
                    State state = monitoredThread.getState();
                    if (state == State.WAITING || state == State.BLOCKED) {
                        tIds.add(monitoredThread.getId());
                    }
                }
                errBuilder.append(getThreadsStacktraces(tIds));
                errorMessages.add(errBuilder.toString());
                deadlocked = true;
                break;
            }
        }
    }
}

From source file:com.kotcrab.vis.editor.util.vis.CrashReporter.java

private void printThreadInfo() {
    println("--- Threads ---");

    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

    for (Thread t : threadSet) {
        println("Thread: " + t.getName() + ", daemon: " + t.isDaemon() + ", state: " + t.getState());
        for (StackTraceElement e : t.getStackTrace()) {
            crashReport.append("\t");
            println(e.toString());/*from   w  w  w. ja  va 2s.  com*/
        }

        println();
    }

    println("---------------");
    println();
}

From source file:voltkvqa.AsyncBenchmark.java

/**
 * Fake an internal jstack to the log/*w ww  .j ava  2s . co  m*/
 */
static public void printJStack() {
    prt(new Date().toString() + " Full thread dump");

    Map<String, List<String>> deduped = new HashMap<String, List<String>>();

    // collect all the output, but dedup the identical stack traces
    for (Entry<Thread, StackTraceElement[]> e : Thread.getAllStackTraces().entrySet()) {
        Thread t = e.getKey();
        String header = String.format("\"%s\" %sprio=%d tid=%d %s", t.getName(), t.isDaemon() ? "daemon " : "",
                t.getPriority(), t.getId(), t.getState().toString());

        String stack = "";
        for (StackTraceElement ste : e.getValue()) {
            stack += "    at " + ste.toString() + "\n";
        }

        if (deduped.containsKey(stack)) {
            deduped.get(stack).add(header);
        } else {
            ArrayList<String> headers = new ArrayList<String>();
            headers.add(header);
            deduped.put(stack, headers);
        }
    }

    for (Entry<String, List<String>> e : deduped.entrySet()) {
        String logline = "";
        for (String header : e.getValue()) {
            logline += header + "\n";
        }
        logline += e.getKey();
        prt(logline);
    }
}

From source file:org.noroomattheinn.utils.ThreadManager.java

public synchronized Thread launch(Runnable r, String name) {
    if (shuttingDown)
        return null;

    Thread t = new Thread(r);
    if (name == null)
        name = String.valueOf(threadID++);
    t.setName("00 VT - " + name);
    t.setDaemon(true);//from  w w  w  .java 2 s  .com
    t.start();
    threads.add(t);

    // Clean out any old terminated threads...
    Iterator<Thread> i = threads.iterator();
    while (i.hasNext()) {
        Thread cur = i.next();
        if (cur.getState() == Thread.State.TERMINATED) {
            i.remove();
        }
    }

    return t;
}