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.apache.metron.integration.components.FluxTopologyComponent.java

public static void assassinateSlots() {
    /*/*from   ww  w. j  a  v a  2 s.c  o m*/
    You might be wondering why I'm not just casting to slot here, but that's because the Slot class moved locations
    and we're supporting multiple versions of storm.
     */
    LOG.error("During slot assassination, all candidate threads: {}", Thread.getAllStackTraces().keySet());
    Thread.getAllStackTraces().keySet().stream()
            .filter(t -> t instanceof AutoCloseable && t.getName().toLowerCase().contains("slot"))
            .forEach(t -> {
                LOG.error("Attempting to close thread: " + t + " with state: " + t.getState());
                // With extreme prejudice.  Safety doesn't matter
                try {
                    t.stop();
                    LOG.error("Called thread.stop() on {}. State is: {}", t.getName(), t.getState());
                } catch (Exception e) {
                    // Just swallow anything arising from the threads being killed.
                }
            });
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.WebSocketTest.java

/**
 * {@inheritDoc}/* w  w w. j a  v  a  2  s  .  co  m*/
 */
@After
@Override
public void releaseResources() {
    super.releaseResources();

    for (final Thread thread : Thread.getAllStackTraces().keySet()) {
        if (thread.getName().contains("WebSocket")) {
            try {
                // ok found one but let's wait a bit an start a second check before
                // pressing the panic button
                Thread.sleep(400);
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    String lastFailing = null;
    for (final java.util.Map.Entry<Thread, StackTraceElement[]> entry : Thread.getAllStackTraces().entrySet()) {
        final Thread thread = entry.getKey();
        if (thread.getName().contains("WebSocket")) {
            lastFailing = thread.getName();
            System.err.println();
            System.err.println("WebSocket thread named '" + lastFailing + "' still running");
            final StackTraceElement[] traces = entry.getValue();
            for (int i = 0; i < traces.length; i++) {
                System.err.println(traces[i]);
            }
        }
    }

    assertNull("WebSocket thread named '" + lastFailing + "' still running", lastFailing);
}

From source file:org.bonitasoft.engine.LocalServerTestsInitializer.java

private void checkThreadsAreStopped() throws InterruptedException {
    System.out.println("=========  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<>();
    final Iterator<Thread> iterator = keySet.iterator();
    while (iterator.hasNext()) {
        final Thread thread = iterator.next();
        if (isExpectedThread(thread)) {
            expectedThreads.add(thread);
        } else {//from ww w  .  java2  s .  c o m
            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 shutdownhook 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;
    System.out.println(nbOfThreads + " are alive. " + nbOfExpectedThreads + " are expected.");
    if (cacheManagerThreads.size() > 2) {
        System.out.println(
                "Only 2 CacheManager threads are expected (PlatformHibernatePersistenceService + TenantHibernatePersistenceService) but "
                        + cacheManagerThreads.size() + " are found:");
        for (Thread thread : cacheManagerThreads) {
            printThread(thread);
        }
    }
    if (unexpectedThreads.size() > 0) {
        System.out.println("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);
    }
    System.out.println("All engine threads are stopped properly");
}

From source file:org.nd4j.linalg.jcublas.context.ContextHolder.java

/**
 * Configure the given information/*www .  ja  va2s.  c om*/
 * based on the device
 */
public void configure() {
    if (confCalled)
        return;

    JCublas2.setExceptionsEnabled(true);
    JCudaDriver.setExceptionsEnabled(true);
    JCuda.setExceptionsEnabled(true);

    if (deviceSetup.get())
        return;

    JCudaDriver.cuInit(0);
    int count[] = new int[1];
    cuDeviceGetCount(count);
    numDevices = count[0];
    log.debug("Found " + numDevices + " gpus");

    if (numDevices < 1)
        numDevices = 1;
    bannedDevices = new ArrayList<>();

    String props = System.getProperty(DEVICES_TO_BAN, "-1");
    String[] split = props.split(",");
    //Should only be used in multi device scenarios; otherwise always use one device
    if (split.length >= 1)
        for (String s : split) {
            Integer i = Integer.parseInt(s);
            if (i >= 0)
                bannedDevices.add(Integer.parseInt(s));

        }

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

    for (int i = 0; i < numDevices; i++) {
        for (Thread thread : threadSet)
            getContext(i, thread.getName());
    }

    setContext();

    try {
        KernelFunctionLoader.getInstance().load();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Check if the device supports mapped host memory
    cudaDeviceProp deviceProperties = new cudaDeviceProp();
    JCuda.cudaGetDeviceProperties(deviceProperties, 0);
    if (deviceProperties.canMapHostMemory == 0) {
        System.err.println("This device can not map host memory");
        System.err.println(deviceProperties.toFormattedString());
        return;
    }

    //force certain ops to have a certain number of threads
    Properties threadProps = new Properties();
    try {
        InputStream is = ContextHolder.class.getResourceAsStream("/function_threads.properties");
        threadProps.load(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (String prop : threadProps.stringPropertyNames()) {
        threads.put(prop, Integer.parseInt(threadProps.getProperty(prop)));
    }

    try {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setJmxEnabled(true);
        config.setBlockWhenExhausted(false);
        config.setMaxIdle(Runtime.getRuntime().availableProcessors());
        config.setMaxTotal(Runtime.getRuntime().availableProcessors());
        config.setMinIdle(Runtime.getRuntime().availableProcessors());
        config.setJmxNameBase("handles");
        handlePool = new CublasHandlePool(new CublasHandlePooledItemFactory(), config);
        GenericObjectPoolConfig confClone = config.clone();
        confClone.setMaxTotal(Runtime.getRuntime().availableProcessors() * 10);
        confClone.setMaxIdle(Runtime.getRuntime().availableProcessors() * 10);
        confClone.setMinIdle(Runtime.getRuntime().availableProcessors() * 10);
        GenericObjectPoolConfig streamConf = confClone.clone();
        streamConf.setJmxNameBase("streams");
        streamPool = new StreamPool(new StreamItemFactory(), streamConf);
        GenericObjectPoolConfig oldStreamConf = streamConf.clone();
        oldStreamConf.setJmxNameBase("oldstream");
        oldStreamPool = new OldStreamPool(new OldStreamItemFactory(), oldStreamConf);
        setContext();
        //seed with multiple streams to encourage parallelism
        for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
            streamPool.addObject();
            oldStreamPool.addObject();
        }

        //force context initialization to occur
        JCuda.cudaFree(Pointer.to(new int[] { 0 }));

    } catch (Exception e) {
        log.warn("Unable to initialize cuda", e);
    }

    for (int i = 0; i < numDevices; i++) {
        ClassPathResource confFile = new ClassPathResource("devices/" + i,
                ContextHolder.class.getClassLoader());
        if (confFile.exists()) {
            Properties props2 = new Properties();
            try {
                props2.load(confFile.getInputStream());
                confs.put(i, new DeviceConfiguration(i, props2));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else
            confs.put(i, new DeviceConfiguration(i));

    }

    confCalled = true;
}

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

/**
 * // w w w . j av  a2 s. 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.powertac.visualizer.services.VisualizerServiceTournament.java

@PreDestroy
private void cleanUp() throws Exception {
    System.out.print("\nCleaning up VisualizerServiceTournament (8) : ");

    // Shutdown the proxy if needed
    if (proxy != null) {
        proxy.shutDown();//from www  .j ava 2s.c om
    }
    System.out.print("1 ");

    // Kill the tick timer
    // I have no idea why this loop is needed
    while (tickTimer == null) {
        try {
            Thread.sleep(100);
        } catch (Exception ignored) {
        }
    }
    System.out.print("2 ");

    tickTimer.cancel();
    tickTimer.purge();
    tickTimer = null;
    System.out.print("3 ");

    if (stateTask != null) {
        stateTask.cancel();
    }
    System.out.print("4 ");

    // Kill the message pump
    try {
        messageFeeder.interrupt();
        messageFeeder.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.print("5 ");

    // Kill the state machine from within
    eventQueue.clear();
    putEvent(Event.quit);
    while (runningStates) {
        try {
            Thread.sleep(100);
        } catch (Exception ignored) {
        }

        if (currentState == loginWait && stateRunner != null
                && stateRunner.getState() == Thread.State.TIMED_WAITING) {
            stateRunner.interrupt();
        }
    }
    System.out.print("6 ");

    try {
        stateRunner.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.print("7 ");

    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread t : threadArray) {
        if (t.getName().contains("Timer-") || t.getName().contains("ActiveMQ")) {
            synchronized (t) {
                t.stop();
            }
        }
    }

    System.out.println("8\n");
}

From source file:org.apache.hadoop.fs.azure.PageBlobOutputStream.java

private void logAllStackTraces() {
    Map liveThreads = Thread.getAllStackTraces();
    for (Iterator i = liveThreads.keySet().iterator(); i.hasNext();) {
        Thread key = (Thread) i.next();
        LOG.debug("Thread " + key.getName());
        StackTraceElement[] trace = (StackTraceElement[]) liveThreads.get(key);
        for (int j = 0; j < trace.length; j++) {
            LOG.debug("\tat " + trace[j]);
        }//from www  . j  ava2s.  co m
    }
}

From source file:de.micromata.genome.util.runtime.debug.PoorMansStackTraceProfiler.java

/**
 * Collect./*from   w ww  .  j  av  a  2 s  . c o  m*/
 */
public void collect() {
    Map<Thread, StackTraceElement[]> ms = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> e : ms.entrySet()) {
        if (e.getKey() == this) {
            continue;
        }
        collect(e.getKey(), e.getValue());

    }
}

From source file:voltkvqa.AsyncBenchmark.java

/**
 * Fake an internal jstack to the log//from  w w  w  .j  a  v  a  2 s. 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:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java

private Thread findServerMainThread() {
    Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
    for (Thread th : map.keySet()) {
        if (th.getName().equals(SERVER_THREAD_NAME)) {
            return th;
        }//from  w  w  w  .  j a va 2 s . c  o  m
    }
    return null;
}