Example usage for java.lang Thread getThreadGroup

List of usage examples for java.lang Thread getThreadGroup

Introduction

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

Prototype

public final ThreadGroup getThreadGroup() 

Source Link

Document

Returns the thread group to which this thread belongs.

Usage

From source file:guru.qas.martini.runtime.harness.MartiniCallable.java

@Override
public MartiniResult call() {
    LOGGER.info("executing scenario {}", martini.getId());
    Thread thread = Thread.currentThread();
    Set<String> categorizations = categories.getCategorizations(martini);

    DefaultMartiniResult result = DefaultMartiniResult.builder()
            .setThreadGroupName(thread.getThreadGroup().getName()).setThreadName(thread.getName())
            .setCategorizations(categorizations).setMartini(martini).setMartiniSuiteIdentifier(suiteIdentifier)
            .build();//from  w  w  w.  j a va 2  s . c o m

    eventManager.publishBeforeScenario(this, result);

    try {
        Map<Step, StepImplementation> stepIndex = martini.getStepIndex();
        result.setStartTimestamp(System.currentTimeMillis());

        DefaultStepResult lastResult = null;
        for (Map.Entry<Step, StepImplementation> mapEntry : stepIndex.entrySet()) {

            Step step = mapEntry.getKey();
            eventManager.publishBeforeStep(this, result);

            StepImplementation implementation = mapEntry.getValue();
            if (null == lastResult || Status.PASSED == lastResult.getStatus()) {
                lastResult = execute(step, implementation);
            } else {
                lastResult = new DefaultStepResult(step, implementation);
                lastResult.setStatus(Status.SKIPPED);
            }
            result.add(lastResult);
            eventManager.publishAfterStep(this, result);
        }
    } finally {
        result.setEndTimestamp(System.currentTimeMillis());
        eventManager.publishAfterScenario(this, result);
    }

    return result;
}

From source file:org.codelibs.fess.servlet.Tomcat6ConfigServlet.java

@SuppressWarnings("deprecation")
private void cleanupAllThreads() {
    final Thread[] threads = getThreads();
    final ClassLoader cl = this.getClass().getClassLoader();
    try {/*from  w w w . jav  a2 s. co m*/
        cl.getResource(null);
    } catch (final Exception e) {
    }

    final List<String> jvmThreadGroupList = new ArrayList<String>();
    jvmThreadGroupList.add("system");
    jvmThreadGroupList.add("RMI Runtime");

    // Iterate over the set of threads
    for (final Thread thread : threads) {
        if (thread != null) {
            final ClassLoader ccl = thread.getContextClassLoader();
            if (ccl != null && ccl.equals(cl)) {
                // Don't warn about this thread
                if (thread == Thread.currentThread()) {
                    continue;
                }

                // Don't warn about JVM controlled threads
                final ThreadGroup tg = thread.getThreadGroup();
                if (tg != null && jvmThreadGroupList.contains(tg.getName())) {
                    continue;
                }

                waitThread(thread);
                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("Interrupting a thread [" + thread.getName() + "]...");
                }
                thread.interrupt();

                waitThread(thread);
                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("Stopping a thread [" + thread.getName() + "]...");
                }
                thread.stop();
            }
        }
    }

    Field threadLocalsField = null;
    Field inheritableThreadLocalsField = null;
    Field tableField = null;
    try {
        threadLocalsField = Thread.class.getDeclaredField("threadLocals");
        threadLocalsField.setAccessible(true);
        inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
        inheritableThreadLocalsField.setAccessible(true);
        // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
        // accessible
        final Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
        tableField = tlmClass.getDeclaredField("table");
        tableField.setAccessible(true);
    } catch (final Exception e) {
        // ignore
    }
    for (final Thread thread : threads) {
        if (thread != null) {

            Object threadLocalMap;
            try {
                // Clear the first map
                threadLocalMap = threadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
            try { // Clear the second map
                threadLocalMap = inheritableThreadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
        }
    }
}

From source file:com.spotify.helios.system.SystemTestBase.java

private void listThreads() {
    final Set<Thread> threads = Thread.getAllStackTraces().keySet();
    final Map<String, Thread> sorted = Maps.newTreeMap();
    for (final Thread t : threads) {
        final ThreadGroup tg = t.getThreadGroup();
        if (t.isAlive() && (tg == null || !tg.getName().equals("system"))) {
            sorted.put(t.getName(), t);/* w ww .j  a va  2 s  .  c o  m*/
        }
    }
    log.info("= THREADS " + Strings.repeat("=", 70));
    for (final Thread t : sorted.values()) {
        final ThreadGroup tg = t.getThreadGroup();
        log.info("{}: \"{}\" ({}{})", t.getId(), t.getName(), (tg == null ? "" : tg.getName() + " "),
                (t.isDaemon() ? "daemon" : ""));
    }
    log.info(Strings.repeat("=", 80));
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadStackTraces(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String stackTrace = "";
            try {
                StackTraceElement[] stack = thread.getStackTrace();
                for (StackTraceElement ste : stack) {
                    stackTrace += ste.getClassName() + "." + ste.getMethodName() + "();" + ste.getFileName()
                            + ":" + ste.getLineNumber() + " ";
                }/*from   w  w w.j a v a2 s.  c  om*/
            } catch (Exception e) {
                stackTrace += "-";
            }
            pw.print(thread.getThreadGroup().getName() + " " + thread.getId() + " " + stackTrace + "\n");
        }
    }
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadDetails(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String threadLocation = "";
            try {
                StackTraceElement ste = thread.getStackTrace()[0];
                StackTraceElement ste2 = thread.getStackTrace()[1];
                threadLocation = ste.getClassName() + "." + ste.getMethodName() + "()," + ste.getFileName()
                        + ":" + ste.getLineNumber() + "," + ste2.getClassName() + "." + ste2.getMethodName()
                        + "()," + ste2.getFileName() + ":" + ste2.getLineNumber();
            } catch (Exception e) {
                threadLocation = "?,?,?,?";
            }/*  ww w  . j  a v a 2s .  c  om*/
            pw.print(thread.getThreadGroup().getName() + "," + thread.getId() + "," + thread.getName() + ","
                    + thread.getPriority() + "," + thread.getState().name() + ","
                    + (thread.isAlive() ? "" : "notalive") + "," + (thread.isDaemon() ? "daemon" : "") + ","
                    + (thread.isInterrupted() ? "interrupted" : "") + "," + threadLocation + "\n");
        }
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads()
 *///from www .j a va 2 s.c o  m
@SuppressWarnings("deprecation")
protected void stopThreads() {
    final Class<?> workerClass = findClass("java.util.concurrent.ThreadPoolExecutor$Worker");
    final Field oracleTarget = findField(Thread.class, "target"); // Sun/Oracle JRE
    final Field ibmRunnable = findField(Thread.class, "runnable"); // IBM JRE

    for (Thread thread : getAllThreads()) {
        @SuppressWarnings("RedundantCast")
        final Runnable runnable = (oracleTarget != null) ? (Runnable) getFieldValue(oracleTarget, thread) : // Sun/Oracle JRE  
                (Runnable) getFieldValue(ibmRunnable, thread); // IBM JRE

        if (thread != Thread.currentThread() && // Ignore current thread
                (isThreadInWebApplication(thread) || isLoadedInWebApplication(runnable))) {

            if (thread.getClass().getName().startsWith(JURT_ASYNCHRONOUS_FINALIZER)) {
                // Note, the thread group of this thread may be "system" if it is triggered by the Garbage Collector
                // however if triggered by us in forceStartOpenOfficeJurtCleanup() it may depend on the application server
                if (stopThreads) {
                    info("Found JURT thread " + thread.getName() + "; starting "
                            + JURTKiller.class.getSimpleName());
                    new JURTKiller(thread).start();
                } else
                    warn("JURT thread " + thread.getName() + " is still running in web app");
            } else if (thread.getThreadGroup() != null && ("system".equals(thread.getThreadGroup().getName()) || // System thread
                    "RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat)

                if ("Keep-Alive-Timer".equals(thread.getName())) {
                    thread.setContextClassLoader(getWebApplicationClassLoader().getParent());
                    debug("Changed contextClassLoader of HTTP keep alive thread");
                }
            } else if (thread.isAlive()) { // Non-system, running in web app

                if ("java.util.TimerThread".equals(thread.getClass().getName())) {
                    if (stopTimerThreads) {
                        warn("Stopping Timer thread running in classloader.");
                        stopTimerThread(thread);
                    } else {
                        info("Timer thread is running in classloader, but will not be stopped");
                    }
                } else {
                    // If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor
                    if (workerClass != null && workerClass.isInstance(runnable)) {
                        if (stopThreads) {
                            warn("Shutting down " + ThreadPoolExecutor.class.getName()
                                    + " running within the classloader.");
                            try {
                                // java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5
                                final Field workerExecutor = findField(workerClass, "this$0");
                                final ThreadPoolExecutor executor = getFieldValue(workerExecutor, runnable);
                                executor.shutdownNow();
                            } catch (Exception ex) {
                                error(ex);
                            }
                        } else
                            info(ThreadPoolExecutor.class.getName()
                                    + " running within the classloader will not be shut down.");
                    }

                    final String displayString = "'" + thread + "' of type " + thread.getClass().getName();

                    if (stopThreads) {
                        final String waitString = (threadWaitMs > 0) ? "after " + threadWaitMs + " ms " : "";
                        warn("Stopping Thread " + displayString + " running in web app " + waitString);

                        if (threadWaitMs > 0) {
                            try {
                                thread.join(threadWaitMs); // Wait for thread to run
                            } catch (InterruptedException e) {
                                // Do nothing
                            }
                        }

                        // Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state.
                        // In this case however, the alternative is a classloader leak, which may or may not be considered worse.
                        if (thread.isAlive())
                            thread.stop();
                    } else {
                        warn("Thread " + displayString + " is still running in web app");
                    }

                }
            }
        }
    }
}

From source file:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java

/**
 * Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads()
 *//*from  w w w  .j a va2  s.  c  om*/
@SuppressWarnings("deprecation")
protected void stopThreads() {
    final Class<?> workerClass = findClass("java.util.concurrent.ThreadPoolExecutor$Worker");
    final Field oracleTarget = findField(Thread.class, "target"); // Sun/Oracle JRE
    final Field ibmRunnable = findField(Thread.class, "runnable"); // IBM JRE

    for (Thread thread : getAllThreads()) {
        final Runnable runnable = (oracleTarget != null) ? (Runnable) getFieldValue(oracleTarget, thread) : // Sun/Oracle JRE  
                (Runnable) getFieldValue(ibmRunnable, thread); // IBM JRE

        if (thread != Thread.currentThread() && // Ignore current thread
                (isThreadInWebApplication(thread) || isLoadedInWebApplication(runnable))) {

            if (thread.getClass().getName().startsWith(JURT_ASYNCHRONOUS_FINALIZER)) {
                // Note, the thread group of this thread may be "system" if it is triggered by the Garbage Collector
                // however if triggered by us in forceStartOpenOfficeJurtCleanup() it may depend on the application server
                if (stopThreads) {
                    info("Found JURT thread " + thread.getName() + "; starting "
                            + JURTKiller.class.getSimpleName());
                    new JURTKiller(thread).start();
                } else
                    warn("JURT thread " + thread.getName() + " is still running in web app");
            } else if (thread.getThreadGroup() != null && ("system".equals(thread.getThreadGroup().getName()) || // System thread
                    "RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat)

                if ("Keep-Alive-Timer".equals(thread.getName())) {
                    thread.setContextClassLoader(getWebApplicationClassLoader().getParent());
                    debug("Changed contextClassLoader of HTTP keep alive thread");
                }
            } else if (thread.isAlive()) { // Non-system, running in web app

                if ("java.util.TimerThread".equals(thread.getClass().getName())) {
                    if (stopTimerThreads) {
                        warn("Stopping Timer thread running in classloader.");
                        stopTimerThread(thread);
                    } else {
                        info("Timer thread is running in classloader, but will not be stopped");
                    }
                } else {
                    // If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor
                    if (workerClass != null && workerClass.isInstance(runnable)) {
                        if (stopThreads) {
                            warn("Shutting down " + ThreadPoolExecutor.class.getName()
                                    + " running within the classloader.");
                            try {
                                // java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5
                                final Field workerExecutor = findField(workerClass, "this$0");
                                final ThreadPoolExecutor executor = getFieldValue(workerExecutor, runnable);
                                executor.shutdownNow();
                            } catch (Exception ex) {
                                error(ex);
                            }
                        } else
                            info(ThreadPoolExecutor.class.getName()
                                    + " running within the classloader will not be shut down.");
                    }

                    final String displayString = "'" + thread + "' of type " + thread.getClass().getName();

                    if (stopThreads) {
                        final String waitString = (threadWaitMs > 0) ? "after " + threadWaitMs + " ms " : "";
                        warn("Stopping Thread " + displayString + " running in web app " + waitString);

                        if (threadWaitMs > 0) {
                            try {
                                thread.join(threadWaitMs); // Wait for thread to run
                            } catch (InterruptedException e) {
                                // Do nothing
                            }
                        }

                        // Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state.
                        // In this case however, the alternative is a classloader leak, which may or may not be considered worse.
                        if (thread.isAlive())
                            thread.stop();
                    } else {
                        warn("Thread " + displayString + " is still running in web app");
                    }

                }
            }
        }
    }
}

From source file:org.regenstrief.util.Util.java

/**
 * Retrieves the parent of the given Thread (not tested)
 * /*from  ww  w. j  ava 2 s . c  om*/
 * @param t the child Thread
 * @return the parent Thread
 **/
public final static Thread getParentThread(final Thread t) {
    final Thread[] g = new Thread[t.getThreadGroup().activeCount()];
    t.getThreadGroup().enumerate(g);

    return g[0];
}

From source file:org.sakaiproject.citation.tool.CitationHelperAction.java

/**
 *
 * @param data/*from   w  w w  .j  av a2  s.c  o m*/
 */
public void doCancelSearch(RunData data) {
    // get state and params
    SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
    ParameterParser params = data.getParameters();

    int requestStateId = params.getInt("requestStateId", 0);
    restoreRequestState(state,
            new String[] { CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX },
            requestStateId);

    // cancel the running search
    ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
    if (search != null) {
        Thread searchThread = search.getSearchThread();
        if (searchThread != null) {
            try {
                searchThread.interrupt();
            } catch (SecurityException se) {
                // not able to interrupt search
                logger.warn("doSearch() [in ThreadGroup " + Thread.currentThread().getThreadGroup().getName()
                        + "] unable to interrupt search Thread [name=" + searchThread.getName() + ", id="
                        + searchThread.getId() + ", group=" + searchThread.getThreadGroup().getName() + "]");
            }
        }
    }

}