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:PrintThread.java

String threadInfo(Thread t) {
    return "thread=" + t.getName() + ", " + "thread group=" + t.getThreadGroup().getName();
}

From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java

@SuppressWarnings("deprecation")
private static void clearReferencesThreads(ClassLoader classLoader) {
    Thread[] threads = getThreads();

    // Iterate over the set of threads
    for (Thread thread : threads) {
        if (thread != null) {
            ClassLoader ccl = thread.getContextClassLoader();
            if (ccl != null && ccl == classLoader) {
                // Don't warn about this thread
                if (thread == Thread.currentThread()) {
                    continue;
                }//w  ww  .j av a 2 s  .c o m

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

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

                // TimerThread is not normally visible
                if (thread.getClass().getName().equals("java.util.TimerThread")) {
                    clearReferencesStopTimerThread(thread);
                    continue;
                }

                if (logger.isLoggable(Level.FINE))
                    logger.fine("A thread named [" + thread.getName()
                            + "] started but has failed to stop it. This is very likely to create a memory leak.");

                // Don't try an stop the threads unless explicitly
                // configured to do so
                if (!clearReferencesStopThreads) {
                    continue;
                }

                // If the thread has been started via an executor, try
                // shutting down the executor
                try {
                    Field targetField = thread.getClass().getDeclaredField("target");
                    targetField.setAccessible(true);
                    Object target = targetField.get(thread);

                    if (target != null && target.getClass().getCanonicalName()
                            .equals("java.util.concurrent.ThreadPoolExecutor.Worker")) {
                        Field executorField = target.getClass().getDeclaredField("this$0");
                        executorField.setAccessible(true);
                        Object executor = executorField.get(target);
                        if (executor instanceof ThreadPoolExecutor) {
                            ((ThreadPoolExecutor) executor).shutdownNow();
                        }
                    }
                } catch (Exception e) {
                    logger.log(Level.WARNING, "Failed to terminate thread named [" + thread.getName() + "]", e);
                }

                // This method is deprecated and for good reason. This is
                // very risky code but is the only option at this point.
                // A *very* good reason for apps to do this clean-up
                // themselves.
                thread.stop();
            }
        }
    }
}

From source file:org.commonjava.indy.diag.data.DiagnosticsManager.java

public String getThreadDumpString() {
    Thread[] threads = new Thread[Thread.activeCount()];
    Thread.enumerate(threads);/*from ww w  . j  ava 2 s. c  o  m*/

    Map<Long, Thread> threadMap = new HashMap<>();
    Stream.of(threads).forEach(t -> threadMap.put(t.getId(), t));
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);

    StringBuilder sb = new StringBuilder();
    Stream.of(threadInfos).forEachOrdered((ti) -> {
        if (sb.length() > 0) {
            sb.append("\n\n");
        }

        String threadGroup = "Unknown";
        Thread t = threadMap.get(ti.getThreadId());
        if (t != null) {
            ThreadGroup tg = t.getThreadGroup();
            if (tg != null) {
                threadGroup = tg.getName();
            }
        }

        sb.append(ti.getThreadName()).append("\n  Group: ").append(threadGroup).append("\n  State: ")
                .append(ti.getThreadState()).append("\n  Lock Info: ").append(ti.getLockInfo())
                .append("\n  Monitors:");

        MonitorInfo[] monitors = ti.getLockedMonitors();
        if (monitors == null || monitors.length < 1) {
            sb.append("  -NONE-");
        } else {
            sb.append("\n  - ").append(join(monitors, "\n  - "));
        }

        sb.append("\n  Trace:\n    ").append(join(ti.getStackTrace(), "\n    "));

    });

    return sb.toString();
}

From source file:com.adito.setup.forms.SystemInfoForm.java

/**
 * Get a thread dump as a string./*from  ww  w  .ja  v  a  2s.  c o  m*/
 * 
 * @return thread dump string
 */
public String getThreadDump() {
    StringBuffer buf = new StringBuffer();
    Thread thread = ContextHolder.getContext().getMainThread();
    if (thread != null) {
        ThreadGroup group = thread.getThreadGroup();
        try {
            if (group != null) {
                dumpThread(group, 0, buf);
            } else {
                buf.append("[No main thread group]");
            }
        } catch (Throwable t) {
            log.error("Failed to get thread dump.", t);
        }
    } else {
        buf.append("[No main thread]");
    }
    return buf.toString();
}

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

private boolean isExpectedThread(final Thread thread) {
    final String name = thread.getName();
    final ThreadGroup threadGroup = thread.getThreadGroup();
    if (threadGroup != null && threadGroup.getName().equals("system")) {
        return true;
    }//from   w w w .j  a  va 2  s  . c  o m
    final List<String> startWithFilter = Arrays.asList("H2 ", "Timer-0" /* postgres driver related */, "BoneCP",
            "bitronix", "main", "Reference Handler", "Signal Dispatcher", "Finalizer",
            "com.google.common.base.internal.Finalizer"/* guava, used by bonecp */, "process reaper",
            "ReaderThread", "Abandoned connection cleanup thread", "AWT-AppKit"/* bonecp related */,
            "Monitor Ctrl-Break"/* Intellij */);
    for (final String prefix : startWithFilter) {
        if (name.startsWith(prefix)) {
            return true;
        }
    }
    return false;
}

From source file:com.brienwheeler.lib.concurrent.NamedThreadFactoryTest.java

@Test
public void testTwoThreadsSameGroup() {
    NamedThreadFactory factory = new NamedThreadFactory();
    factory.setName(NAME);/*from w  w  w . ja  v a2s . co  m*/
    Thread thread1 = factory.newThread(new NullRunnable());
    Assert.assertEquals(NAME + "-1", thread1.getName());
    Thread thread2 = factory.newThread(new NullRunnable());
    Assert.assertEquals(NAME + "-2", thread2.getName());
    Assert.assertEquals(thread1.getThreadGroup(), thread2.getThreadGroup());
}

From source file:org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.java

public void printActiveThreads() {
    System.out.println("=========================================");
    System.out.println("Thread.activeCount() = " + Thread.activeCount());

    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
    Set<String> groups = allStackTraces.keySet().stream()
            .filter(t -> t.getThreadGroup() == null || !t.getThreadGroup().getName().equals("system"))
            .map(t -> String.valueOf(t.getThreadGroup())).collect(Collectors.toSet());

    for (String group : groups) {
        System.out.println("group = " + group);
        for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) {
            Thread thread = entry.getKey();
            if (String.valueOf(thread.getThreadGroup()).equals(group)) {
                System.out.println("\t[" + thread.getId() + "] " + thread.toString() + ":" + thread.getState());
            }/*from www. j  a  va2 s. c  o m*/
        }
    }
    System.out.println("=========================================");
}

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

private boolean isExpectedThread(final Thread thread) {
    final String name = thread.getName();
    final ThreadGroup threadGroup = thread.getThreadGroup();
    if (threadGroup != null && threadGroup.getName().equals("system")) {
        return true;
    }/*from w w  w .jav  a 2 s  .c o  m*/
    final List<String> startWithFilter = Arrays.asList("H2 ", "Timer-0" /* postgres driver related */,
            "bitronix", "main", "Reference Handler", "Signal Dispatcher", "Finalizer",
            "com.google.common.base.internal.Finalizer", "process reaper", "ReaderThread",
            "Abandoned connection cleanup thread", "Monitor Ctrl-Break"/* Intellij */, "daemon-shutdown",
            "surefire-forkedjvm", "Restlet");
    for (final String prefix : startWithFilter) {
        if (name.startsWith(prefix)) {
            return true;
        }
    }
    //shutdown hook not executed in main thread
    return thread.getId() == Thread.currentThread().getId();
}

From source file:ThreadViewer.java

private void createPendingCellData() {
    Thread[] thread = findAllThreads();
    Object[][] cell = new Object[thread.length][columnCount];

    for (int i = 0; i < thread.length; i++) {
        Thread t = thread[i];
        Object[] rowCell = cell[i];

        rowCell[0] = new Integer(t.getPriority());
        rowCell[1] = new Boolean(t.isAlive());
        rowCell[2] = new Boolean(t.isDaemon());
        rowCell[3] = new Boolean(t.isInterrupted());
        rowCell[4] = t.getThreadGroup().getName();
        rowCell[5] = t.getName();/*from w ww  .  ja v a2s .c  o m*/
    }

    synchronized (dataLock) {
        pendingCellData = cell;
    }
}

From source file:com.brienwheeler.lib.concurrent.NamedThreadFactoryTest.java

@Test
public void testTwoFactoriesSameName() {
    NamedThreadFactory factory1 = new NamedThreadFactory();
    factory1.setName(NAME);//w w  w . j ava2s. c  o  m
    Thread thread1 = factory1.newThread(new NullRunnable());
    Assert.assertEquals(NAME + "-1", thread1.getName());

    NamedThreadFactory factory2 = new NamedThreadFactory();
    factory2.setName(NAME);
    Thread thread2 = factory2.newThread(new NullRunnable());
    Assert.assertEquals(NAME + "-1", thread2.getName());

    Assert.assertNotSame(thread1.getThreadGroup(), thread2.getThreadGroup());
}