Example usage for java.lang Thread getAllStackTraces

List of usage examples for java.lang Thread getAllStackTraces

Introduction

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

Prototype

public static Map<Thread, StackTraceElement[]> getAllStackTraces() 

Source Link

Document

Returns a map of stack traces for all live threads.

Usage

From source file:org.midonet.midolman.Midolman.java

public static void dumpStacks() {
    Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
    for (Thread thread : traces.keySet()) {
        System.err.print("\"" + thread.getName() + "\" ");
        if (thread.isDaemon())
            System.err.print("daemon ");
        System.err.print(String.format("prio=%x tid=%x %s [%x]\n", thread.getPriority(), thread.getId(),
                thread.getState(), System.identityHashCode(thread)));

        StackTraceElement[] trace = traces.get(thread);
        for (StackTraceElement e : trace) {
            System.err.println("        at " + e.toString());
        }/*from  w ww.  j  a v a2  s  .  c o m*/
    }
}

From source file:com.palantir.docker.compose.execution.CommandShould.java

@Ignore
@Test//from w ww . ja v  a  2s  .c om
public void not_create_long_lived_threads_after_execution() throws IOException, InterruptedException {
    int preThreadCount = Thread.getAllStackTraces().entrySet().size();
    dockerComposeCommand.execute(errorHandler, "rm", "-f");
    int postThreadCount = Thread.getAllStackTraces().entrySet().size();
    assertThat("command thread pool has exited", preThreadCount == postThreadCount);
}

From source file:com.streamsets.datacollector.main.TestLogConfigurator.java

@Test
public void testConfigDirLog4jConfig() throws IOException {
    RuntimeInfo runtimeInfo = Mockito.mock(RuntimeInfo.class);
    File configDir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(configDir.mkdirs());
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("log4j.properties");
    OutputStream os = new FileOutputStream(new File(configDir, "log4j.properties"));
    IOUtils.copy(is, os);/*  ww w  .j  a  v a 2  s  . c  om*/
    is.close();
    os.close();
    Mockito.when(runtimeInfo.getConfigDir()).thenReturn(configDir.getAbsolutePath());
    Mockito.when(runtimeInfo.getLog4jPropertiesFileName()).thenReturn("log4j.properties");
    new LogConfigurator(runtimeInfo).configure();
    Mockito.verify(runtimeInfo, Mockito.times(1)).getConfigDir();
    boolean foundFileWatcher = false;
    for (Thread thread : Thread.getAllStackTraces().keySet()) {
        foundFileWatcher |= (thread instanceof FileWatchdog);
    }
    Assert.assertTrue(foundFileWatcher);
    Mockito.verify(runtimeInfo, Mockito.times(1))
            .setAttribute(Mockito.eq(RuntimeInfo.LOG4J_CONFIGURATION_URL_ATTR), Mockito.any());
}

From source file:com.jkoolcloud.tnt4j.streams.StreamsAgentTest.java

@Test
public void testRunFromAPI() throws Exception {
    final String testStreamName = "TestStream"; // NON-NLS
    final File tempConfFile = File.createTempFile("testConfigutarion", ".xml");
    FileWriter fw = new FileWriter(tempConfFile);
    String sb = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Utils.NEW_LINE + "<tnt-data-source"
            + Utils.NEW_LINE // NON-NLS
            + "        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + Utils.NEW_LINE // NON-NLS
            + "        xsi:noNamespaceSchemaLocation=\"https://raw.githubusercontent.com/Nastel/tnt4j-streams/master/config/tnt-data-source.xsd\">" // NON-NLS
            + Utils.NEW_LINE + "    <stream name=\"" + testStreamName // NON-NLS
            + "\" class=\"com.jkoolcloud.tnt4j.streams.inputs.CharacterStream\">" + Utils.NEW_LINE // NON-NLS
            + "        <property name=\"HaltIfNoParser\" value=\"false\"/>" + Utils.NEW_LINE // NON-NLS
            + "        <property name=\"Port\" value=\"9595\"/>" + Utils.NEW_LINE + "    </stream>"
            + Utils.NEW_LINE // NON-NLS
            + "</tnt-data-source>"; // NON-NLS
    fw.write(sb);/*from   w  w  w.j a v  a 2s . c  o m*/
    fw.flush();
    Utils.close(fw);
    StreamsAgent.runFromAPI(tempConfFile.getAbsolutePath());
    Thread.sleep(500);
    tempConfFile.delete();
    final Set<Thread> threads = Thread.getAllStackTraces().keySet();
    for (Thread thread : threads) {
        if (thread.getName().contains(testStreamName)) {
            return;
        } else {
            continue;
        }
    }
    fail("No streams thread created");
}

From source file:org.trafodion.rest.ResourceChecker.java

public void logInfo(Phase phase, String tagLine) {
    long threadCount = rc.getThreadsCount(phase);
    LOG.info(tagLine + ": " + threadCount + " threads"
            + (initialThreadsCount > 0 ? " (was " + initialThreadsCount + "), " : ", ")
            + rc.getOpenFileDescriptorCount() + " file descriptors"
            + (initialFileHandlesCount > 0 ? " (was " + initialFileHandlesCount + "). " : " ")
            + (initialThreadsCount > 0 && threadCount > initialThreadsCount ? " -thread leak?- " : "")
            + (initialFileHandlesCount > 0 && rc.getOpenFileDescriptorCount() > initialFileHandlesCount
                    ? " -file handle leak?- "
                    : ""));
    if (phase == Phase.END) {
        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
        if (stackTraces.size() > initialThreadNames.size()) {
            for (Thread t : stackTraces.keySet()) {
                if (!initialThreadNames.contains(t.getName())) {
                    LOG.info(tagLine + ": potentially hanging thread - " + t.getName());
                    StackTraceElement[] stackElements = stackTraces.get(t);
                    for (StackTraceElement ele : stackElements) {
                        LOG.info("\t" + ele);
                    }//  w  ww  . ja va  2 s . c  o m
                }
            }
        }
    }
}

From source file:org.bonitasoft.engine.test.internal.EngineStarter.java

protected void checkThreadsAreStopped() throws InterruptedException {
    LOGGER.info("=========  CHECK ENGINE IS SHUTDOWN =======");
    final Set<Thread> keySet = Thread.getAllStackTraces().keySet();
    List<Thread> expectedThreads = new ArrayList<>();
    List<Thread> cacheManagerThreads = new ArrayList<>();
    List<Thread> unexpectedThreads = new ArrayList<>();
    for (Thread thread : keySet) {
        if (isExpectedThread(thread)) {
            expectedThreads.add(thread);
        } else {/*from  w w  w  .  java 2s  .c om*/
            if (isCacheManager(thread)) {
                cacheManagerThreads.add(thread);
            } else {
                unexpectedThreads.add(thread);
            }
        }
    }
    //2 cache manager threads are allowed
    // one for PlatformHibernatePersistenceService
    // one for TenantHibernatePersistenceService
    // there is no clean way to kill them, a shutdown hook is doing this
    // killing them using hibernate implementation classes is causing weird behaviours
    int nbOfThreads = keySet.size();
    int nbOfExpectedThreads = expectedThreads.size() + 2;
    boolean fail = nbOfThreads > nbOfExpectedThreads;
    LOGGER.info(nbOfThreads + " threads are alive. " + nbOfExpectedThreads + " are expected.");
    if (cacheManagerThreads.size() > 2) {
        LOGGER.info(
                "Only 2 CacheManager threads are expected (PlatformHibernatePersistenceService + TenantHibernatePersistenceService) but "
                        + cacheManagerThreads.size() + " are found:");
        for (Thread thread : cacheManagerThreads) {
            printThread(thread);
        }
    }
    if (unexpectedThreads.size() > 0) {
        LOGGER.info("The following list of threads is not expected:");
        for (Thread thread : unexpectedThreads) {
            printThread(thread);
        }
    }
    if (fail) {
        throw new IllegalStateException("Some threads are still active : \nCacheManager potential issues:"
                + cacheManagerThreads + "\nOther threads:" + unexpectedThreads);
    }
    LOGGER.info("All engine threads are stopped properly");
}

From source file:org.elasticsearch.network.DirectBufferNetworkTests.java

/**
 * Validates that all the thread local allocated ByteBuffer in sun.nio under the Util$BufferCache
 * are not greater than 1mb.//  w ww. j  a  va  2  s. c  o  m
 */
private void validateNoLargeDirectBufferAllocated() throws Exception {
    // Make the fields in the Thread class that store ThreadLocals
    // accessible
    Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
    threadLocalsField.setAccessible(true);
    // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
    // accessible
    Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
    Field tableField = tlmClass.getDeclaredField("table");
    tableField.setAccessible(true);

    for (Thread thread : Thread.getAllStackTraces().keySet()) {
        if (thread == null) {
            continue;
        }
        Object threadLocalMap = threadLocalsField.get(thread);
        if (threadLocalMap == null) {
            continue;
        }
        Object[] table = (Object[]) tableField.get(threadLocalMap);
        if (table == null) {
            continue;
        }
        for (Object entry : table) {
            if (entry == null) {
                continue;
            }
            Field valueField = entry.getClass().getDeclaredField("value");
            valueField.setAccessible(true);
            Object value = valueField.get(entry);
            if (value == null) {
                continue;
            }
            if (!value.getClass().getName().equals("sun.nio.ch.Util$BufferCache")) {
                continue;
            }
            Field buffersField = value.getClass().getDeclaredField("buffers");
            buffersField.setAccessible(true);
            Object[] buffers = (Object[]) buffersField.get(value);
            for (Object buffer : buffers) {
                if (buffer == null) {
                    continue;
                }
                assertThat(((ByteBuffer) buffer).capacity(), Matchers.lessThan(1 * 1024 * 1024));
            }
        }
    }

}

From source file:org.trafodion.rest.ResourceChecker.java

/**
 * Helper function: print the threads/*from  w  w w. j av a 2  s  .  co  m*/
 */
public static void printThreads() {
    Set<Thread> threads = Thread.getAllStackTraces().keySet();
    System.out.println("name; state; isDameon; isAlive; isInterrupted");
    for (Thread t : threads) {
        System.out.println(t.getName() + ";" + t.getState() + ";" + t.isDaemon() + ";" + t.isAlive() + ";"
                + t.isInterrupted());
    }
}

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);//from   w  ww .  ja v  a  2  s .  c  om
    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:org.openflamingo.remote.thrift.thriftfs.ThriftHandlerBase.java

/**
 * Return a list of threads that currently exist with their stack traces
 *//*  w ww  .  j ava  2s.  c o m*/
public List<ThreadStackTrace> getThreadDump(RequestContext ctx) {
    List<ThreadStackTrace> dump = new ArrayList<ThreadStackTrace>();

    Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> entry : traces.entrySet()) {
        final Thread t = entry.getKey();
        final StackTraceElement[] frames = entry.getValue();

        ThreadStackTrace tst = new ThreadStackTrace();
        tst.threadName = t.getName();
        tst.threadStringRepresentation = String.valueOf(t);
        tst.isDaemon = t.isDaemon();
        tst.stackTrace = new ArrayList<StackTraceElement>();
        for (StackTraceElement ste : frames) {
            StackTraceElement tFrame = new StackTraceElement();
            tFrame.className = ste.getClassName();
            tFrame.fileName = ste.getFileName();
            tFrame.lineNumber = ste.getLineNumber();
            tFrame.methodName = ste.getMethodName();
            tFrame.isNativeMethod = ste.isNativeMethod();
            tFrame.stringRepresentation = String.valueOf(ste);
            tst.stackTrace.add(tFrame);
        }
        dump.add(tst);
    }
    return dump;
}