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:de.dal33t.powerfolder.PowerFolder.java

/**
 * Starts a PowerFolder controller with the given command line arguments
 *
 * @param args//www  . ja  va 2s .  c  o  m
 */
public static void startPowerFolder(String[] args) {

    // Touch Logger immediately to initialize handlers.
    LoggingManager.isLogToFile();

    // Default exception logger
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e);
        }
    });

    CommandLine commandLine = parseCommandLine(args);
    if (commandLine == null) {
        return;
    }

    // -l --log console log levels (severe, warning, info, fine and finer).
    if (commandLine.hasOption("l")) {
        String levelName = commandLine.getOptionValue("l");
        Level level = LoggingManager.levelForName(levelName);
        if (level != null) {
            LoggingManager.setConsoleLogging(level);
        }
    }

    if (commandLine.hasOption("s")) {
        // Server mode, suppress debug output on console
        // Logger.addExcludeConsoleLogLevel(Logger.DEBUG);
    }

    if (commandLine.hasOption("h")) {
        // Show help
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS);
        return;
    }

    int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue());
    String portStr = commandLine.getOptionValue("k");
    if (StringUtils.isNotBlank(portStr)) {
        try {
            rconPort = Integer.valueOf(portStr.trim());
        } catch (Exception e) {
            log.warning("Unable to parse rcon port: " + portStr + ". " + e);
        }
    }

    boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort);

    if (commandLine.hasOption("k")) {
        if (runningInstanceFound) {
            System.out.println("Stopping " + NAME);
            // Send quit command
            RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT);
        } else {
            System.err.println("Process not running");
        }

        // stop
        return;
    }

    // set language from commandline to preferences
    if (commandLine.hasOption("g")) {
        Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g"));
    }

    if (JavaVersion.systemVersion().isOpenJDK()) {
        Object[] options = { "Open Oracle home page and exit", "Exit" };

        int n = JOptionPane.showOptionDialog(null,
                "You are using OpenJDK which is unsupported.\n"
                        + "Please install the client with bundled JRE or install the Oracle JRE",
                "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);

        if (n == 0) {
            try {
                BrowserLauncher.openURL("http://www.java.com");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return;
    }

    // The controller.
    Controller controller = Controller.createController();

    String[] files = commandLine.getArgs();
    // Parsing of command line completed

    boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e")
            || commandLine.hasOption("r") || commandLine.hasOption("a");
    // Try to start controller
    boolean startController = !commandContainsRemoteCommands || !runningInstanceFound;
    try {
        log.info("PowerFolder v" + Controller.PROGRAM_VERSION);

        // Start controller
        if (startController) {
            controller.startConfig(commandLine);
        }

        // Send remote command if there a files in commandline
        if (files != null && files.length > 0) {
            // Parse filenames and build remote command
            StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN);

            for (String file : files) {
                openFilesRCommand.append(file);
                // FIXME: Add ; separator ?
            }

            // Send remote command to running PowerFolder instance
            RemoteCommandManager.sendCommand(openFilesRCommand.toString());
        }

        if (commandLine.hasOption("e")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e"));
        }
        if (commandLine.hasOption("r")) {
            RemoteCommandManager
                    .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r"));
        }
        if (commandLine.hasOption("a")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a"));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        log.log(Level.SEVERE, "Throwable", t);
        return;
    }

    // Begin monitoring memory usage.
    if (controller.isStarted() && controller.isUIEnabled()) {
        ScheduledExecutorService service = controller.getThreadPool();
        service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES);
    }

    // Not go into console mode if ui is open
    if (!startController) {
        if (runningInstanceFound) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI);
        }
        return;
    }

    System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------");

    boolean restartRequested = false;
    do {
        // Go into restart loop
        while (controller.isStarted() || controller.isShuttingDown()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.log(Level.WARNING, "InterruptedException", e);
                return;
            }
        }

        restartRequested = controller.isRestartRequested();
        if (restartRequested) {
            Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
            for (Thread thread : threads.keySet()) {
                if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector")
                        || thread.getName().startsWith("ConHandler")) {
                    thread.interrupt();
                }
            }
            log.info("Restarting controller");
            System.out.println(
                    "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------");
            controller = null;
            System.gc();
            controller = Controller.createController();
            // Start controller
            controller.startConfig(commandLine);
        }
    } while (restartRequested);
}

From source file:org.eclipse.jubula.rc.swing.listener.ComponentHandler.java

/**
 * Pretty prints the stack traces of all currently running threads to the 
 * log.//  w  ww  . j  a va2  s.  co m
 */
private static void logStacktrace() {
    if (TRACE_COMPONENT_NOT_FOUND) {
        StringBuilder builder = new StringBuilder();
        builder.append("Logging stacktrace:" + SystemUtils.LINE_SEPARATOR); //$NON-NLS-1$
        Thread currentThread = Thread.currentThread();
        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
        for (Entry<Thread, StackTraceElement[]> stackTrace : stackTraces.entrySet()) {

            Thread thread = stackTrace.getKey();

            if (thread == currentThread) {
                builder.append("[current-thread] - "); //$NON-NLS-1$
            }

            builder.append(thread.getName() + ":" + SystemUtils.LINE_SEPARATOR); //$NON-NLS-1$
            for (StackTraceElement e : stackTrace.getValue()) {
                builder.append("\t" + e + SystemUtils.LINE_SEPARATOR); //$NON-NLS-1$
            }

        }

        builder.append(SystemUtils.LINE_SEPARATOR);
        log.warn(builder);
    }
}

From source file:majordodo.task.BrokerTestUtils.java

public static String getThreadName(long threadid) {
    for (Thread t : Thread.getAllStackTraces().keySet()) {
        if (t.getId() == threadid) {
            return t.getName();
        }/* w  w  w .j ava2 s . c  o  m*/
    }
    return null;
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

public static List<ThreadInformations> buildThreadInformationsList() {
    final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    final Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
    final List<Thread> threads = new ArrayList<Thread>(stackTraces.keySet());

    // si "1.6.0_01".compareTo(Parameters.JAVA_VERSION) > 0;
    // on rcuprait les threads sans stack trace en contournant bug 6434648 avant 1.6.0_01
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648
    // hormis pour le thread courant qui obtient sa stack trace diffremment sans le bug
    //      threads = getThreadsFromThreadGroups();
    //      final Thread currentThread = Thread.currentThread();
    //      stackTraces = Collections.singletonMap(currentThread, currentThread.getStackTrace());

    final boolean cpuTimeEnabled = threadBean.isThreadCpuTimeSupported() && threadBean.isThreadCpuTimeEnabled();
    final long[] deadlockedThreads = getDeadlockedThreads(threadBean);
    final List<ThreadInformations> threadInfosList = new ArrayList<ThreadInformations>(threads.size());
    // hostAddress rcupr ici car il peut y avoir plus de 20000 threads
    final String hostAddress = Parameters.getHostAddress();
    for (final Thread thread : threads) {
        final StackTraceElement[] stackTraceElements = stackTraces.get(thread);
        final List<StackTraceElement> stackTraceElementList = stackTraceElements == null ? null
                : new ArrayList<StackTraceElement>(Arrays.asList(stackTraceElements));
        final long cpuTimeMillis;
        final long userTimeMillis;
        if (cpuTimeEnabled) {
            cpuTimeMillis = threadBean.getThreadCpuTime(thread.getId()) / 1000000;
            userTimeMillis = threadBean.getThreadUserTime(thread.getId()) / 1000000;
        } else {//from   ww  w . ja  v  a  2  s.c om
            cpuTimeMillis = -1;
            userTimeMillis = -1;
        }
        final boolean deadlocked = deadlockedThreads != null
                && Arrays.binarySearch(deadlockedThreads, thread.getId()) >= 0;
        // stackTraceElementList est une ArrayList et non unmodifiableList pour lisibilit xml
        threadInfosList.add(new ThreadInformations(thread, stackTraceElementList, cpuTimeMillis, userTimeMillis,
                deadlocked, hostAddress));
    }
    // on retourne ArrayList et non unmodifiableList pour lisibilit du xml par xstream
    return threadInfosList;
}

From source file:com.googlecode.concurrentlinkedhashmap.MultiThreadedTest.java

private void handleTimout(ConcurrentLinkedHashMap<?, ?> cache, ExecutorService es, TimeoutException e) {
    for (StackTraceElement[] trace : Thread.getAllStackTraces().values()) {
        for (StackTraceElement element : trace) {
            info("\tat " + element);
        }//  ww  w.jav a2s  .  co  m
        if (trace.length > 0) {
            info("------");
        }
    }
    es.shutdownNow();
    try {
        es.awaitTermination(10, SECONDS);
    } catch (InterruptedException ex) {
        fail("", ex);
    }

    // Print the state of the cache
    debug("Cached Elements: %s", cache.toString());
    debug("Deque Forward:\n%s", ascendingToString(cache));
    debug("Deque Backward:\n%s", descendingToString(cache));

    // Print the recorded failures
    for (String failure : failures) {
        debug(failure);
    }
    fail("Spun forever", e);
}

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 .  ja  va 2  s  .c  om
        }
    }
    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 initMemoryMonitor() {
    ConfigurationService configurationService = GlobalResourceLoader.getService("kualiConfigurationService");
    if (NumberUtils.isNumber(configurationService.getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY))) {
        if (Double.valueOf(configurationService.getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY)) > 0) {
            LOG.info("Starting up MemoryMonitor thread");
            MemoryMonitor.setPercentageUsageThreshold(Double
                    .valueOf(configurationService.getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY)));
            memoryMonitor = new MemoryMonitor("OLE Memory Monitor: Over "
                    + configurationService.getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY)
                    + "% Memory Used");
            memoryMonitor.addListener(new MemoryMonitor.Listener() {
                org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(MemoryMonitor.class);

                @Override//from w w  w . j ava 2 s  . c o  m
                public void memoryUsageLow(String springContextId, Map<String, String> memoryUsageStatistics,
                        String deadlockedThreadIds) {
                    StringBuilder logStatement = new StringBuilder(springContextId).append("\n\tMemory Usage");
                    for (String memoryType : memoryUsageStatistics.keySet()) {
                        logStatement.append("\n\t\t").append(memoryType.toUpperCase()).append(": ")
                                .append(memoryUsageStatistics.get(memoryType));
                    }
                    logStatement.append("\n\tLocked Thread Ids: ").append(deadlockedThreadIds)
                            .append("\n\tThread Stacks");
                    for (Map.Entry<Thread, StackTraceElement[]> threadStackTrace : Thread.getAllStackTraces()
                            .entrySet()) {
                        logStatement.append("\n\t\tThread: name=").append(threadStackTrace.getKey().getName())
                                .append(", id=").append(threadStackTrace.getKey().getId()).append(", priority=")
                                .append(threadStackTrace.getKey().getPriority()).append(", state=")
                                .append(threadStackTrace.getKey().getState());
                        for (StackTraceElement stackTraceElement : threadStackTrace.getValue()) {
                            logStatement.append("\n\t\t\t").append(stackTraceElement);
                        }
                    }
                    LOG.warn(logStatement);
                    MemoryMonitor.setPercentageUsageThreshold(0.95);
                }
            });
        }
    } else {
        LOG.warn(MEMORY_MONITOR_THRESHOLD_KEY + " is not a number: "
                + configurationService.getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY));
    }
}

From source file:org.openmrs.util.OpenmrsClassLoader.java

/**
 * Sets the class loader, for all threads referencing a destroyed openmrs class loader, 
 * to the current one.//from   w w  w .j  a  va2 s  .  c  om
 */
public static void setThreadsToNewClassLoader() {
    //Give ownership of all threads loaded by the old class loader to the new one.
    //Examples of such threads are: Keep-Alive-Timer, MySQL Statement Cancellation Timer, etc
    //That way they will no longer hold onto the destroyed OpenmrsClassLoader and hence
    //allow it to be garbage collected after a spring application context refresh, when a new one is created.
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread thread : threadArray) {

        ClassLoader classLoader = thread.getContextClassLoader();

        //Some threads have a null class loader reference. e.g Finalizer, Reference Handler, etc
        if (classLoader == null) {
            continue;
        }

        //Threads referencing the current class loader are good.
        if (classLoader == getInstance()) {
            continue;
        }

        //For threads referencing any destroyed class loader, point them to the new one.
        if (classLoader instanceof OpenmrsClassLoader) {
            thread.setContextClassLoader(getInstance());
        }
    }
}

From source file:org.kuali.kfs.sys.context.SpringContext.java

static void initMemoryMonitor() {
    if (NumberUtils.isNumber(KRADServiceLocator.getKualiConfigurationService()
            .getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY))) {
        if (Double.valueOf(KRADServiceLocator.getKualiConfigurationService()
                .getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY)) > 0) {
            LOG.info("Starting up MemoryMonitor thread");
            MemoryMonitor.setPercentageUsageThreshold(Double.valueOf(KRADServiceLocator
                    .getKualiConfigurationService().getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY)));
            memoryMonitor = new MemoryMonitor(
                    "KFS Memory Monitor: Over " + KRADServiceLocator.getKualiConfigurationService()
                            .getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY) + "% Memory Used");
            memoryMonitor.addListener(new MemoryMonitor.Listener() {
                org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(MemoryMonitor.class);

                @Override//from   w  w w .  ja v  a2  s  .  c om
                public void memoryUsageLow(String springContextId, Map<String, String> memoryUsageStatistics,
                        String deadlockedThreadIds) {
                    StringBuilder logStatement = new StringBuilder(springContextId).append("\n\tMemory Usage");
                    for (String memoryType : memoryUsageStatistics.keySet()) {
                        logStatement.append("\n\t\t").append(memoryType.toUpperCase()).append(": ")
                                .append(memoryUsageStatistics.get(memoryType));
                    }
                    logStatement.append("\n\tLocked Thread Ids: ").append(deadlockedThreadIds)
                            .append("\n\tThread Stacks");
                    for (Map.Entry<Thread, StackTraceElement[]> threadStackTrace : Thread.getAllStackTraces()
                            .entrySet()) {
                        logStatement.append("\n\t\tThread: name=").append(threadStackTrace.getKey().getName())
                                .append(", id=").append(threadStackTrace.getKey().getId()).append(", priority=")
                                .append(threadStackTrace.getKey().getPriority()).append(", state=")
                                .append(threadStackTrace.getKey().getState());
                        for (StackTraceElement stackTraceElement : threadStackTrace.getValue()) {
                            logStatement.append("\n\t\t\t").append(stackTraceElement);
                        }
                    }
                    LOG.warn(logStatement);
                    MemoryMonitor.setPercentageUsageThreshold(0.95);
                }
            });
        }
    } else {
        LOG.warn(MEMORY_MONITOR_THRESHOLD_KEY + " is not a number: " + KRADServiceLocator
                .getKualiConfigurationService().getPropertyValueAsString(MEMORY_MONITOR_THRESHOLD_KEY));
    }
}

From source file:wordnice.utils.JavaUtils.java

public static Thread[] getThreads() {
    try {// w  ww  . j a va 2s  .  c  o  m
        getThreads = Thread.class.getDeclaredMethod("getThreads");
        getThreads.setAccessible(true);
        return (Thread[]) getThreads.invoke(null);
    } catch (Throwable t) {
    }
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    return threadSet.toArray(new Thread[threadSet.size()]);
}