Search in sources :

Example 21 with ThreadInfo

use of java.lang.management.ThreadInfo in project cassandra by apache.

the class DatabaseDescriptorRefTest method testDatabaseDescriptorRef.

@Test
public void testDatabaseDescriptorRef() throws Throwable {
    PrintStream out = System.out;
    PrintStream err = System.err;
    ThreadMXBean threads = ManagementFactory.getThreadMXBean();
    int threadCount = threads.getThreadCount();
    ClassLoader delegate = Thread.currentThread().getContextClassLoader();
    List<Pair<String, Exception>> violations = Collections.synchronizedList(new ArrayList<>());
    ClassLoader cl = new ClassLoader(null) {

        final Map<String, Class<?>> classMap = new HashMap<>();

        public URL getResource(String name) {
            return delegate.getResource(name);
        }

        public InputStream getResourceAsStream(String name) {
            return delegate.getResourceAsStream(name);
        }

        protected Class<?> findClass(String name) throws ClassNotFoundException {
            Class<?> cls = classMap.get(name);
            if (cls != null)
                return cls;
            if (name.startsWith("org.apache.cassandra.")) {
                if (!checkedClasses.contains(name))
                    violations.add(Pair.create(name, new Exception()));
            }
            URL url = delegate.getResource(name.replace('.', '/') + ".class");
            if (url == null)
                throw new ClassNotFoundException(name);
            try (InputStream in = url.openConnection().getInputStream()) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                int c;
                while ((c = in.read()) != -1) os.write(c);
                byte[] data = os.toByteArray();
                cls = defineClass(name, data, 0, data.length);
                classMap.put(name, cls);
                return cls;
            } catch (IOException e) {
                throw new ClassNotFoundException(name, e);
            }
        }
    };
    Thread.currentThread().setContextClassLoader(cl);
    assertEquals("thread started", threadCount, threads.getThreadCount());
    Class cDatabaseDescriptor = Class.forName("org.apache.cassandra.config.DatabaseDescriptor", true, cl);
    for (String methodName : new String[] { "clientInitialization", "applyAddressConfig", "applyInitialTokens", // "applySnitch",
    "applyEncryptionContext" }) {
        Method method = cDatabaseDescriptor.getDeclaredMethod(methodName);
        method.invoke(null);
        if ("clientInitialization".equals(methodName) && threadCount + 1 == threads.getThreadCount()) {
            // ignore the "AsyncAppender-Worker-ASYNC" thread
            threadCount++;
        }
        if (threadCount != threads.getThreadCount()) {
            for (ThreadInfo threadInfo : threads.getThreadInfo(threads.getAllThreadIds())) out.println("Thread #" + threadInfo.getThreadId() + ": " + threadInfo.getThreadName());
            assertEquals("thread started in " + methodName, threadCount, ManagementFactory.getThreadMXBean().getThreadCount());
        }
        checkViolations(err, violations);
    }
}
Also used : PrintStream(java.io.PrintStream) ThreadMXBean(java.lang.management.ThreadMXBean) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Method(java.lang.reflect.Method) IOException(java.io.IOException) URL(java.net.URL) ThreadInfo(java.lang.management.ThreadInfo) HashMap(java.util.HashMap) Map(java.util.Map) Pair(org.apache.cassandra.utils.Pair) Test(org.junit.Test)

Example 22 with ThreadInfo

use of java.lang.management.ThreadInfo in project cassandra by apache.

the class ToolsTester method assertNoUnexpectedThreadsStarted.

public void assertNoUnexpectedThreadsStarted(String[] expectedThreadNames, String[] optionalThreadNames) {
    ThreadMXBean threads = ManagementFactory.getThreadMXBean();
    Set<String> initial = initialThreads.stream().map(ThreadInfo::getThreadName).collect(Collectors.toSet());
    Set<String> current = Arrays.stream(threads.getThreadInfo(threads.getAllThreadIds())).map(ThreadInfo::getThreadName).collect(Collectors.toSet());
    List<Pattern> expected = expectedThreadNames != null ? Arrays.stream(expectedThreadNames).map(Pattern::compile).collect(Collectors.toList()) : Collections.emptyList();
    List<Pattern> optional = optionalThreadNames != null ? Arrays.stream(optionalThreadNames).map(Pattern::compile).collect(Collectors.toList()) : Collections.emptyList();
    current.removeAll(initial);
    List<Pattern> notPresent = expected.stream().filter(threadNamePattern -> !current.stream().anyMatch(threadName -> threadNamePattern.matcher(threadName).matches())).collect(Collectors.toList());
    Set<String> remain = current.stream().filter(threadName -> expected.stream().anyMatch(pattern -> pattern.matcher(threadName).matches())).filter(threadName -> optional.stream().anyMatch(pattern -> pattern.matcher(threadName).matches())).collect(Collectors.toSet());
    if (!current.isEmpty())
        System.err.println("Unexpected thread names: " + remain);
    if (!notPresent.isEmpty())
        System.err.println("Mandatory thread missing: " + notPresent);
    assertTrue("Wrong thread status", remain.isEmpty() && notPresent.isEmpty());
}
Also used : Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) ThreadMXBean(java.lang.management.ThreadMXBean) Collectors(java.util.stream.Collectors) File(java.io.File) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) ThreadInfo(java.lang.management.ThreadInfo) Permission(java.security.Permission) Assert.assertFalse(org.junit.Assert.assertFalse) Assert.fail(org.junit.Assert.fail) ManagementFactory(java.lang.management.ManagementFactory) Pattern(java.util.regex.Pattern) Method(java.lang.reflect.Method) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ThreadMXBean(java.lang.management.ThreadMXBean) Pattern(java.util.regex.Pattern)

Example 23 with ThreadInfo

use of java.lang.management.ThreadInfo in project bazel by bazelbuild.

the class StackTraces method printAll.

/**
   * Prints all stack traces to the given stream.
   *
   * @param out Stream to print to
   */
public static void printAll(PrintStream out) {
    out.println("Starting full thread dump ...\n");
    ThreadMXBean mb = ManagementFactory.getThreadMXBean();
    // ThreadInfo has comprehensive information such as locks.
    ThreadInfo[] threadInfos = mb.dumpAllThreads(true, true);
    // But we can know whether a thread is daemon only from Thread
    Set<Thread> threads = Thread.getAllStackTraces().keySet();
    Map<Long, Thread> threadMap = new HashMap<>();
    for (Thread thread : threads) {
        threadMap.put(thread.getId(), thread);
    }
    // Dump non-daemon threads first
    for (ThreadInfo threadInfo : threadInfos) {
        Thread thread = threadMap.get(threadInfo.getThreadId());
        if (thread != null && !thread.isDaemon()) {
            dumpThreadInfo(threadInfo, thread, out);
        }
    }
    // Dump daemon threads
    for (ThreadInfo threadInfo : threadInfos) {
        Thread thread = threadMap.get(threadInfo.getThreadId());
        if (thread != null && thread.isDaemon()) {
            dumpThreadInfo(threadInfo, thread, out);
        }
    }
    long[] deadlockedThreads = mb.findDeadlockedThreads();
    if (deadlockedThreads != null) {
        out.println("Detected deadlocked threads: " + Arrays.toString(deadlockedThreads));
    }
    long[] monitorDeadlockedThreads = mb.findMonitorDeadlockedThreads();
    if (monitorDeadlockedThreads != null) {
        out.println("Detected monitor deadlocked threads: " + Arrays.toString(monitorDeadlockedThreads));
    }
    out.println("\nDone full thread dump.");
    out.flush();
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) ThreadInfo(java.lang.management.ThreadInfo) HashMap(java.util.HashMap)

Example 24 with ThreadInfo

use of java.lang.management.ThreadInfo in project jdk8u_jdk by JetBrains.

the class TestThread method waitUntilBlockingOnObject.

/**
     * Waits until {@link TestThread} is in the certain {@link State}
     * and blocking on {@code object}.
     *
     * @param state The thread state
     * @param object The object to block on
     */
public void waitUntilBlockingOnObject(Thread.State state, Object object) {
    String want = object == null ? null : object.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(object));
    ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
    while (isAlive()) {
        ThreadInfo ti = tmx.getThreadInfo(getId());
        if (ti.getThreadState() == state && (want == null || want.equals(ti.getLockName()))) {
            return;
        }
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) ThreadInfo(java.lang.management.ThreadInfo)

Example 25 with ThreadInfo

use of java.lang.management.ThreadInfo in project jdk8u_jdk by JetBrains.

the class ThreadMXBeanStateTest method getThreadInfo.

private static ThreadInfo getThreadInfo(ThreadStateController t, Thread.State expected) {
    // wait for the thread to transition to the expected state.
    // There is a small window between the thread checking the state
    // and the thread actual entering that state.
    int retryCount = 0;
    ThreadInfo info = tm.getThreadInfo(t.getId());
    while (info.getThreadState() != expected && retryCount < MAX_RETRY) {
        ThreadStateController.pause(10);
        retryCount++;
        info = tm.getThreadInfo(t.getId());
    }
    return info;
}
Also used : ThreadInfo(java.lang.management.ThreadInfo)

Aggregations

ThreadInfo (java.lang.management.ThreadInfo)107 ThreadMXBean (java.lang.management.ThreadMXBean)43 HashMap (java.util.HashMap)9 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8 HashSet (java.util.HashSet)6 Map (java.util.Map)6 LockInfo (java.lang.management.LockInfo)5 MonitorInfo (java.lang.management.MonitorInfo)5 Date (java.util.Date)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 Test (org.junit.Test)4 FileOutputStream (java.io.FileOutputStream)3 PrintStream (java.io.PrintStream)3 PrintWriter (java.io.PrintWriter)3 Method (java.lang.reflect.Method)3 LinkedHashSet (java.util.LinkedHashSet)3 TreeMap (java.util.TreeMap)3 ExecutorService (java.util.concurrent.ExecutorService)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2