本文整理汇总了Java中java.lang.management.ThreadMXBean.getThreadInfo方法的典型用法代码示例。如果您正苦于以下问题:Java ThreadMXBean.getThreadInfo方法的具体用法?Java ThreadMXBean.getThreadInfo怎么用?Java ThreadMXBean.getThreadInfo使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.lang.management.ThreadMXBean
的用法示例。
在下文中一共展示了ThreadMXBean.getThreadInfo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: countTimerThreads
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
private static int countTimerThreads() {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
int count = 0;
ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
for (ThreadInfo info : infos) {
if (info == null) continue;
for (StackTraceElement elem : info.getStackTrace()) {
if (elem.getClassName().contains("Timer")) {
count++;
break;
}
}
}
return count;
}
示例2: countThreads
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
/**
* Count the number of threads that have a stack frame containing
* the given string
*/
protected static int countThreads(String search) {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
int count = 0;
ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
for (ThreadInfo info : infos) {
if (info == null) continue;
for (StackTraceElement elem : info.getStackTrace()) {
if (elem.getClassName().contains(search)) {
count++;
break;
}
}
}
return count;
}
示例3: waitUntilBlockingOnObject
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
/**
* 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) {
}
}
}
示例4: waitForBlock
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
static void waitForBlock(Thread t) {
Thread currentThread = Thread.currentThread();
System.out.println("waiting for thread " + t.getName() + " to block " +
"on a lock held by thread " + currentThread.getName());
ThreadMXBean tm = ManagementFactory.getThreadMXBean();
while (true) {
ThreadInfo ti = tm.getThreadInfo(t.getId());
if (ti == null) {
System.out.println(" thread has exited");
return;
}
if (ti.getLockOwnerId() == currentThread.getId()) {
System.out.println(" thread now blocked");
return;
}
Thread.yield();
}
}
示例5: dump
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
public static ThreadInfo[] dump(int maxDepth,boolean onlyDeadLock){
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
long[] ids ;
if(onlyDeadLock) {
ids = threadBean.findDeadlockedThreads();
}else {
ids = threadBean.getAllThreadIds();
}
if(ids !=null) {
return threadBean.getThreadInfo(ids, maxDepth);
}
else {
return null;
}
}
示例6: buildDeadlockInfo
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
static String buildDeadlockInfo() {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
long[] threadIds = threadBean.findMonitorDeadlockedThreads();
if (threadIds != null && threadIds.length > 0) {
StringWriter stringWriter = new StringWriter();
PrintWriter out = new PrintWriter(stringWriter);
ThreadInfo[] infos = threadBean.getThreadInfo(threadIds, true, true);
for (ThreadInfo ti : infos) {
printThreadInfo(ti, out);
printLockInfo(ti.getLockedSynchronizers(), out);
out.println();
}
out.close();
return stringWriter.toString();
} else {
return null;
}
}
示例7: countThreads
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
/**
* Count the number of threads that have a stack frame containing
* the given string
*/
private static int countThreads(String search) {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
int count = 0;
ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
for (ThreadInfo info : infos) {
if (info == null) continue;
for (StackTraceElement elem : info.getStackTrace()) {
if (elem.getClassName().contains(search)) {
count++;
break;
}
}
}
return count;
}
示例8: anyThreadMatching
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
/**
* Determine if there are any threads whose name matches the regex.
* @param pattern a Pattern object used to match thread names
* @return true if there is any thread that matches the pattern
*/
public static boolean anyThreadMatching(Pattern pattern) {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos =
threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
for (ThreadInfo info : infos) {
if (info == null)
continue;
if (pattern.matcher(info.getThreadName()).matches()) {
return true;
}
}
return false;
}
示例9: main
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
CountDownLatch prepareLatch = new CountDownLatch(2);
AtomicInteger goLatch = new AtomicInteger(1);
Task taskA = new Task(prepareLatch, goLatch, AnnA.class);
Task taskB = new Task(prepareLatch, goLatch, AnnB.class);
taskA.start();
taskB.start();
// wait until both threads start-up
prepareLatch.await();
// let them go
goLatch.set(0);
// obtain ThreadMXBean
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
// wait for threads to finish or dead-lock
while (taskA.isAlive() || taskB.isAlive()) {
// attempt to join threads
taskA.join(500L);
taskB.join(500L);
// detect dead-lock
long[] deadlockedIds = threadBean.findMonitorDeadlockedThreads();
if (deadlockedIds != null && deadlockedIds.length > 0) {
StringBuilder sb = new StringBuilder("deadlock detected:\n\n");
for (ThreadInfo ti : threadBean.getThreadInfo(deadlockedIds, Integer.MAX_VALUE)) {
sb.append(ti);
}
throw new IllegalStateException(sb.toString());
}
}
}
示例10: waitUntilBlockingOnObject
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
/**
* Waits until {@link Thread} is in the certain {@link Thread.State}
* and blocking on {@code object}.
*
* @param state The thread state
* @param object The object to block on
*/
public static void waitUntilBlockingOnObject(Thread thread, Thread.State state, Object object)
throws InterruptedException {
String want = object == null ? null : object.getClass().getName() + '@'
+ Integer.toHexString(System.identityHashCode(object));
ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
while (thread.isAlive()) {
ThreadInfo ti = tmx.getThreadInfo(thread.getId());
if (ti.getThreadState() == state
&& (want == null || want.equals(ti.getLockName()))) {
return;
}
Thread.sleep(1);
}
}
示例11: assertNoThreadsMatching
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
/**
* Assert that there are no threads running whose name matches the
* given regular expression.
* @param regex the regex to match against
*/
public static void assertNoThreadsMatching(String regex) {
Pattern pattern = Pattern.compile(regex);
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
for (ThreadInfo info : infos) {
if (info == null) continue;
if (pattern.matcher(info.getThreadName()).matches()) {
Assert.fail("Leaked thread: " + info + "\n" +
Joiner.on("\n").join(info.getStackTrace()));
}
}
}
示例12: printServerState
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
@Override
public String printServerState() {
final long ONE_MB = 1024 * 1024;
String newLine = "\n";
StringBuilder result = new StringBuilder();
try {
long freeMemory = Runtime.getRuntime().freeMemory() / ONE_MB; // 空闲内存
long totalMemory = Runtime.getRuntime().totalMemory() / ONE_MB; // 当前内存
long maxMemory = Runtime.getRuntime().maxMemory() / ONE_MB; // 最大可使用内存
result.append(String.format("freeMemory: %s mb", freeMemory)).append(newLine);
result.append(String.format(String.format("usedMemory: %s mb", (totalMemory - freeMemory)))).append(newLine);
result.append(String.format("totalMemory: %s mb", totalMemory)).append(newLine);
result.append(String.format("maxMemory: %s mb", maxMemory)).append(newLine);
MemoryMXBean memoryMXBean = getMemoryMXBean();
result.append(String.format("heap memory used: %s mb", memoryMXBean.getHeapMemoryUsage().getUsed() / ONE_MB)).append(newLine);
result.append(String.format("heap memory usage: %s", memoryMXBean.getHeapMemoryUsage())).append(newLine);
result.append(String.format("nonHeap memory usage: %s", memoryMXBean.getNonHeapMemoryUsage())).append(newLine);
List<BufferPoolMXBean> buffMXBeans = (List<BufferPoolMXBean>) getPlatformMXBeans(BufferPoolMXBean.class);
for (BufferPoolMXBean buffMXBean : buffMXBeans) {
result.append(String.format("buffer pool[%s]: used %s mb, total %s mb", buffMXBean.getName(),
buffMXBean.getMemoryUsed() / ONE_MB, buffMXBean.getTotalCapacity() / ONE_MB)).append(newLine);
}
List<GarbageCollectorMXBean> gcMXBeans = getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcBean : gcMXBeans) {
result.append(String.format("%s 发生 %s 次 gc, gc 总共消耗 %s 毫秒", gcBean.getName(), gcBean.getCollectionCount(), gcBean.getCollectionTime())).append(newLine);
}
ThreadMXBean threadMXBean = getThreadMXBean();
int nThreadRun = 0;
int nThreadBlocked = 0;
int nThreadWaiting = 0;
for (long threadId : threadMXBean.getAllThreadIds()) {
ThreadInfo threadInfo = threadMXBean.getThreadInfo(threadId);
if (threadInfo.getThreadState() == Thread.State.RUNNABLE) {
nThreadRun++;
}
if (threadInfo.getThreadState() == Thread.State.BLOCKED) {
nThreadBlocked++;
}
if (threadInfo.getThreadState() == Thread.State.WAITING) {
nThreadWaiting++;
}
}
result.append(String.format("活跃线程数 %s, 阻塞线程数 %s, 等待线程数 %s", nThreadRun, nThreadBlocked, nThreadWaiting)).append(newLine);
} catch (Exception e) {
LoggerUtils.error("", e);
}
return result.toString();
}
示例13: doThreadUpdates
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
private void doThreadUpdates() {
ThreadMXBean threadMXBean =
ManagementFactory.getThreadMXBean();
long threadIds[] =
threadMXBean.getAllThreadIds();
ThreadInfo[] threadInfos =
threadMXBean.getThreadInfo(threadIds, 0);
int threadsNew = 0;
int threadsRunnable = 0;
int threadsBlocked = 0;
int threadsWaiting = 0;
int threadsTimedWaiting = 0;
int threadsTerminated = 0;
for (ThreadInfo threadInfo : threadInfos) {
// threadInfo is null if the thread is not alive or doesn't exist
if (threadInfo == null) continue;
Thread.State state = threadInfo.getThreadState();
if (state == NEW) {
threadsNew++;
}
else if (state == RUNNABLE) {
threadsRunnable++;
}
else if (state == BLOCKED) {
threadsBlocked++;
}
else if (state == WAITING) {
threadsWaiting++;
}
else if (state == TIMED_WAITING) {
threadsTimedWaiting++;
}
else if (state == TERMINATED) {
threadsTerminated++;
}
}
metrics.setMetric("threadsNew", threadsNew);
metrics.setMetric("threadsRunnable", threadsRunnable);
metrics.setMetric("threadsBlocked", threadsBlocked);
metrics.setMetric("threadsWaiting", threadsWaiting);
metrics.setMetric("threadsTimedWaiting", threadsTimedWaiting);
metrics.setMetric("threadsTerminated", threadsTerminated);
}
示例14: testBug70704
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
/**
* Tests fix for Bug#70704 - Deadlock using UpdatableResultSet.
*
* Doesn't actually test the buggy behavior since it is not verifiable since the fix for Bug#59462 (revision 385a151). However, the patch for this fix is
* needed because the synchronization in UpdatableResultSet was dated.
* This test makes sure there is no regression.
*
* WARNING! If this test fails there is no guarantee that the JVM will remain stable and won't affect any other tests. It is imperative that this test
* passes to ensure other tests results.
*/
public void testBug70704() throws Exception {
for (int i = 0; i < 100; i++) {
final Statement testStmt = this.conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
final ResultSet testRs = testStmt.executeQuery("SELECT 1");
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new Callable<Void>() {
public Void call() throws Exception {
testStmt.close();
return null;
}
});
executorService.submit(new Callable<Void>() {
public Void call() throws Exception {
testRs.close();
return null;
}
});
executorService.shutdown();
if (!executorService.awaitTermination(2, TimeUnit.SECONDS)) {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
long[] threadIds = threadMXBean.findMonitorDeadlockedThreads();
if (threadIds != null) {
System.err.println("Deadlock detected!");
ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
for (ThreadInfo ti : threadInfos) {
System.err.println();
System.err.println(ti);
System.err.println("Stack trace:");
for (StackTraceElement ste : ti.getStackTrace()) {
System.err.println(" " + ste);
}
}
fail("Unexpected deadlock detected. Consult system output for more details. WARNING: this failure may lead to JVM instability.");
}
}
}
}
示例15: assertAllThreadsStopped
import java.lang.management.ThreadMXBean; //导入方法依赖的package包/类
protected void assertAllThreadsStopped() throws InterruptedException {
Set<String> failedThreads = new HashSet<>();
int attempts = 3;
for (int i = 0; i < attempts; i++) {
ThreadMXBean jmx = ManagementFactory.getThreadMXBean();
ThreadInfo[] threads = jmx.getThreadInfo(jmx.getAllThreadIds());
for (ThreadInfo t : threads) {
if (t != null && t.getThreadState() != Thread.State.TERMINATED) {
String name = t.getThreadName();
if (!FAILED_THREAD_NAMES_CACHE.contains(name)) {
String nameLower = name.toLowerCase();
if (KNOWN_THREAD_PREFIXES.stream().noneMatch(nameLower::startsWith)) {
failedThreads.add(name);
}
}
}
}
if (failedThreads.isEmpty()) {
break;
}
if (i < attempts - 1) {
failedThreads.clear();
Thread.sleep(BUSY_WAIT_INTERVAL);
}
}
if (!failedThreads.isEmpty()) {
FAILED_THREAD_NAMES_CACHE.addAll(failedThreads);
}
assertTrue(failedThreads.toString(), failedThreads.isEmpty());
}