Java Code Examples for java.lang.management.ThreadInfo

The following are top voted examples for showing how to use java.lang.management.ThreadInfo. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: TestThread.java   Source Code and License 6 votes vote down vote up
/**
 * 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) {
        }
    }
}
 
Example 2
Project: incubator-netbeans   File: NbTestCase.java   Source Code and License 6 votes vote down vote up
private static StringBuilder printThread(ThreadInfo ti, StringBuilder sb) {
    sb.append("\"" + ti.getThreadName() + "\"" + " Id="
            + ti.getThreadId() + " in " + ti.getThreadState());
    if (ti.getLockName() != null) {
        sb.append(" waiting on lock=" + ti.getLockName());
    }
    if (ti.isSuspended()) {
        sb.append(" (suspended)");
    }
    if (ti.isInNative()) {
        sb.append(" (running in native)");
    }
    sb.append("\n");
    if (ti.getLockOwnerName() != null) {
        sb.append("\t owned by " + ti.getLockOwnerName() + " Id="
                + ti.getLockOwnerId()).append("\n");
    }
    return sb;
}
 
Example 3
Project: jdk8u-jdk   File: ThreadImpl.java   Source Code and License 6 votes vote down vote up
public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth) {
    verifyThreadIds(ids);

    if (maxDepth < 0) {
        throw new IllegalArgumentException(
            "Invalid maxDepth parameter: " + maxDepth);
    }

    // ids has been verified to be non-null
    // an empty array of ids should return an empty array of ThreadInfos
    if (ids.length == 0) return new ThreadInfo[0];

    Util.checkMonitorAccess();

    ThreadInfo[] infos = new ThreadInfo[ids.length]; // nulls
    if (maxDepth == Integer.MAX_VALUE) {
        getThreadInfo1(ids, -1, infos);
    } else {
        getThreadInfo1(ids, maxDepth, infos);
    }
    return infos;
}
 
Example 4
Project: incubator-netbeans   File: SamplesOutputStream.java   Source Code and License 6 votes vote down vote up
private void internStackTrace(ThreadInfo tinfo) {
    if (steCache == null) {
        return;
    }

    StackTraceElement[] stack = tinfo.getStackTrace();

    for (int i = 0; i < stack.length; i++) {
        StackTraceElement ste = stack[i];
        WeakReference<StackTraceElement> oldStackRef = steCache.get(ste);

        if (oldStackRef != null) {
            stack[i] = oldStackRef.get();
            assert stack[i] != null;
        } else {
            steCache.put(ste, new WeakReference(ste));
        }
    }
}
 
Example 5
Project: dremio-oss   File: ThreadsIterator.java   Source Code and License 6 votes vote down vote up
public ThreadsIterator(final SabotContext dbContext, final OperatorContext context) {
  this.dbContext = dbContext;
  threadMXBean = ManagementFactory.getThreadMXBean();
  final long[] ids = threadMXBean.getAllThreadIds();

  final Iterator<Long> threadIdIterator = Longs.asList(ids).iterator();

  this.threadInfoIterator = Iterators.filter(
    Iterators.transform(threadIdIterator, new Function<Long, ThreadInfo>() {

      @Override
      public ThreadInfo apply(Long input) {
        return threadMXBean.getThreadInfo(input, 100);
      }
    }),
    Predicates.notNull());

  logger.debug("number of threads = {}, number of cores = {}", ids.length, NUMBER_OF_CORES);

  this.stats = dbContext.getWorkStatsProvider().get();
}
 
Example 6
Project: jdk8u-jdk   File: ThreadInfoCompositeData.java   Source Code and License 6 votes vote down vote up
public static void badNameCompositeData() throws Exception {
    CompositeType ct =
        new CompositeType("MyCompositeType",
                          "CompositeType for ThreadInfo",
                          badItemNames,
                          badItemNames,
                          validItemTypes);
    CompositeData cd =
        new CompositeDataSupport(ct,
                                 badItemNames,
                                 values);

    try {
        ThreadInfo info = ThreadInfo.from(cd);
    } catch (IllegalArgumentException e) {
        System.out.println("Expected exception: " +
            e.getMessage());
        return;
    }
    throw new RuntimeException(
        "IllegalArgumentException not thrown");
}
 
Example 7
Project: incubator-netbeans   File: ThreadDumpWindow.java   Source Code and License 6 votes vote down vote up
private void printThreads(final StringBuilder sb, ThreadDump td) {
    ThreadInfo[] threads = td.getThreads();
    boolean goToSourceAvailable = GoToSource.isAvailable();
    boolean jdk15 = td.isJDK15();

    sb.append("<pre>"); // NOI18N
    sb.append(" <b>Full thread dump: "); // NOI18N
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  // NOI18N
    sb.append(df.format(td.getTime()) + "</b><br><br>");
    for (ThreadInfo thread : threads) {
        if (thread != null) {
            if (jdk15) {
                print15Thread(sb, thread, goToSourceAvailable);
            } else {
                print16Thread(sb, thread, goToSourceAvailable);
            }
        }
    }
    sb.append("</pre>"); // NOI18N
}
 
Example 8
Project: incubator-netbeans   File: ThreadDumpWindow.java   Source Code and License 6 votes vote down vote up
private void print15Thread(final StringBuilder sb, final ThreadInfo thread, boolean goToSourceAvailable) {
    sb.append("<br>\"" + thread.getThreadName() + // NOI18N
            "\" - Thread [email protected]" + thread.getThreadId() + "<br>");    // NOI18N
    sb.append("   java.lang.Thread.State: " + thread.getThreadState()); // NOI18N
    if (thread.getLockName() != null) {
        sb.append(" on " + thread.getLockName());   // NOI18N
        if (thread.getLockOwnerName() != null) {
            sb.append(" owned by: " + thread.getLockOwnerName());   // NOI18N
        }
    }
    sb.append("<br>");    // NOI18N
    for (StackTraceElement st : thread.getStackTrace()) {
        String stackElementText = htmlize(st.toString());
        String stackEl = stackElementText;
        if (goToSourceAvailable) {
            String className = st.getClassName();
            String method = st.getMethodName();
            int lineNo = st.getLineNumber();
            String stackUrl = OPEN_THREADS_URL + className + "|" + method + "|" + lineNo; // NOI18N
            stackEl = "<a href=\"" + stackUrl + "\">" + stackElementText + "</a>";    // NOI18N
        }
        sb.append("        at ").append(stackEl).append("<br>");    // NOI18N
    }
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: Diagnostics.java   Source Code and License 6 votes vote down vote up
/**
 * Formats the thread dump header for one thread.
 *
 * @param ti the ThreadInfo describing the thread
 * @return the formatted thread dump header
 */
private static String getThreadDumpHeader(ThreadInfo ti) {
    StringBuilder sb = new StringBuilder("\"" + ti.getThreadName() + "\"");
    sb.append(" Id=" + ti.getThreadId());
    sb.append(" cpu=" + threadMXBean.getThreadCpuTime(ti.getThreadId()) +
              " ns");
    sb.append(" usr=" + threadMXBean.getThreadUserTime(ti.getThreadId()) +
              " ns");
    sb.append(" blocked " + ti.getBlockedCount() + " for " +
              ti.getBlockedTime() + " ms");
    sb.append(" waited " + ti.getWaitedCount() + " for " +
              ti.getWaitedTime() + " ms");

    if (ti.isSuspended()) {
        sb.append(" (suspended)");
    }
    if (ti.isInNative()) {
        sb.append(" (running in native)");
    }
    sb.append(CRLF);
    sb.append(INDENT3 + "java.lang.Thread.State: " + ti.getThreadState());
    sb.append(CRLF);
    return sb.toString();
}
 
Example 10
Project: AgentWorkbench   File: LoadMeasureJVM.java   Source Code and License 6 votes vote down vote up
/**
 * This method return true/false if a Thread, given by it's name exists or not.
 * @param threadName2LookAt the name of the thread
 * @return boolean true, if the named thread exists
 */
public boolean threadExists(String threadName2LookAt) {
	
	boolean exists = false;
	
	long[] jvmThreadIDs = threadXB.getAllThreadIds();
	ThreadInfo[] jvmThreadInfo = threadXB.getThreadInfo(jvmThreadIDs);
	for (int i = 0; i < jvmThreadInfo.length; i++) {
		String threadName = jvmThreadInfo[i].getThreadName();
		if (threadName.equalsIgnoreCase(threadName2LookAt)) {
			exists = true;
			break;
		}
	}
	return exists;		
}
 
Example 11
Project: openjdk-jdk10   File: GraalOSRLockTest.java   Source Code and License 6 votes vote down vote up
public static boolean isMonitorLockHeldByThread(Object o, Thread t) {
    int oihc = System.identityHashCode(o);
    ThreadMXBean tmxbean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] tinfos = tmxbean.dumpAllThreads(true, false);

    for (ThreadInfo ti : tinfos) {
        if (!(t != null && t.getId() != ti.getThreadId())) {
            for (MonitorInfo mi : ti.getLockedMonitors()) {
                if (mi.getIdentityHashCode() == oihc) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 12
Project: hadoop-oss   File: JvmMetrics.java   Source Code and License 6 votes vote down vote up
private void getThreadUsage(MetricsRecordBuilder rb) {
  int threadsNew = 0;
  int threadsRunnable = 0;
  int threadsBlocked = 0;
  int threadsWaiting = 0;
  int threadsTimedWaiting = 0;
  int threadsTerminated = 0;
  long threadIds[] = threadMXBean.getAllThreadIds();
  for (ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadIds, 0)) {
    if (threadInfo == null) continue; // race protection
    switch (threadInfo.getThreadState()) {
      case NEW:           threadsNew++;           break;
      case RUNNABLE:      threadsRunnable++;      break;
      case BLOCKED:       threadsBlocked++;       break;
      case WAITING:       threadsWaiting++;       break;
      case TIMED_WAITING: threadsTimedWaiting++;  break;
      case TERMINATED:    threadsTerminated++;    break;
    }
  }
  rb.addGauge(ThreadsNew, threadsNew)
    .addGauge(ThreadsRunnable, threadsRunnable)
    .addGauge(ThreadsBlocked, threadsBlocked)
    .addGauge(ThreadsWaiting, threadsWaiting)
    .addGauge(ThreadsTimedWaiting, threadsTimedWaiting)
    .addGauge(ThreadsTerminated, threadsTerminated);
}
 
Example 13
Project: jdk8u-jdk   File: TestLogConfigurationDeadLock.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    while(goOn) {
        try {
            long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
            checkCount.incrementAndGet();
            ids = ids == null ? new long[0] : ids;
            if (ids.length == 1) {
                throw new RuntimeException("Found 1 deadlocked thread: "+ids[0]);
            } else if (ids.length > 0) {
                ThreadInfo[] infos = ManagementFactory.getThreadMXBean()
                    .getThreadInfo(ids, Integer.MAX_VALUE);
                System.err.println("Found "+ids.length+" deadlocked threads: ");
                for (ThreadInfo inf : infos) {
                    System.err.println(inf.toString());
                }
                throw new RuntimeException("Found "+ids.length+" deadlocked threads");
            }
            Thread.sleep(100);
        } catch(InterruptedException | RuntimeException x) {
            fail(x);
        }
    }
}
 
Example 14
Project: hadoop-oss   File: TestShell.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 15
Project: hadoop-oss   File: TimedOutTestsListener.java   Source Code and License 6 votes vote down vote up
private static void printThreadInfo(ThreadInfo ti, PrintWriter out) {
  // print thread information
  printThread(ti, out);

  // print stack trace with locks
  StackTraceElement[] stacktrace = ti.getStackTrace();
  MonitorInfo[] monitors = ti.getLockedMonitors();
  for (int i = 0; i < stacktrace.length; i++) {
    StackTraceElement ste = stacktrace[i];
    out.println(INDENT + "at " + ste.toString());
    for (MonitorInfo mi : monitors) {
      if (mi.getLockedStackDepth() == i) {
        out.println(INDENT + "  - locked " + mi);
      }
    }
  }
  out.println();
}
 
Example 16
Project: apache-tomcat-7.0.73-with-comment   File: Diagnostics.java   Source Code and License 6 votes vote down vote up
/**
 * Check if any threads are deadlocked. If any, print
 * the thread dump for those threads.
 *
 * @return a deadlock message and the formatted thread dump
 *         of the deadlocked threads
 */
private static String findDeadlock() {
    ThreadInfo[] tinfos = null;
    long[] ids = threadMXBean.findDeadlockedThreads();
    if (ids != null) {
        tinfos = threadMXBean.getThreadInfo(threadMXBean.findDeadlockedThreads(),
                                            true, true);
        if (tinfos != null) {
            StringBuilder sb =
                new StringBuilder("Deadlock found between the following threads:");
            sb.append(CRLF);
            sb.append(getThreadDump(tinfos));
            return sb.toString();
        }
    }
    return "";
}
 
Example 17
Project: openjdk-jdk10   File: ConcurrentAssociateTest.java   Source Code and License 6 votes vote down vote up
/**
 * A debugging tool to print stack traces of most threads, as jstack does.
 * Uninteresting threads are filtered out.
 */
static void dumpTestThreads() {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    System.err.println("------ stacktrace dump start ------");
    for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
        String name = info.getThreadName();
        if ("Signal Dispatcher".equals(name))
            continue;
        if ("Reference Handler".equals(name)
            && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
            continue;
        if ("Finalizer".equals(name)
            && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
            continue;
        System.err.print(info);
    }
    System.err.println("------ stacktrace dump end ------");
}
 
Example 18
Project: openjdk-jdk10   File: ThreadMXBeanStateTest.java   Source Code and License 6 votes vote down vote up
private static void checkSuspendedThreadState(ThreadStateController t, Thread.State state) {
    ThreadInfo info = getThreadInfo(t, state);
    if (info == null) {
        throw new RuntimeException(t.getName() +
           " expected to have ThreadInfo " +
           " but got null.");
    }

    if (info.getThreadState() != state) {
        throw new RuntimeException(t.getName() + " expected to be in " +
            state + " state but got " + info.getThreadState());
    }

    if (!info.isSuspended()) {
        throw new RuntimeException(t.getName() + " expected to be suspended " +
            " but isSuspended() returns " + info.isSuspended());
    }
}
 
Example 19
Project: openjdk-jdk10   File: ThreadImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth) {
    verifyThreadIds(ids);

    if (maxDepth < 0) {
        throw new IllegalArgumentException(
            "Invalid maxDepth parameter: " + maxDepth);
    }

    // ids has been verified to be non-null
    // an empty array of ids should return an empty array of ThreadInfos
    if (ids.length == 0) return new ThreadInfo[0];

    Util.checkMonitorAccess();

    ThreadInfo[] infos = new ThreadInfo[ids.length]; // nulls
    if (maxDepth == Integer.MAX_VALUE) {
        getThreadInfo1(ids, -1, infos);
    } else {
        getThreadInfo1(ids, maxDepth, infos);
    }
    return infos;
}
 
Example 20
Project: cornerstone   File: ThreadingManager.java   Source Code and License 6 votes vote down vote up
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;
    }


}
 
Example 21
Project: tomcat7   File: Diagnostics.java   Source Code and License 6 votes vote down vote up
/**
 * Formats the thread dump header for one thread.
 *
 * @param ti the ThreadInfo describing the thread
 * @return the formatted thread dump header
 */
private static String getThreadDumpHeader(ThreadInfo ti) {
    StringBuilder sb = new StringBuilder("\"" + ti.getThreadName() + "\"");
    sb.append(" Id=" + ti.getThreadId());
    sb.append(" cpu=" + threadMXBean.getThreadCpuTime(ti.getThreadId()) +
              " ns");
    sb.append(" usr=" + threadMXBean.getThreadUserTime(ti.getThreadId()) +
              " ns");
    sb.append(" blocked " + ti.getBlockedCount() + " for " +
              ti.getBlockedTime() + " ms");
    sb.append(" waited " + ti.getWaitedCount() + " for " +
              ti.getWaitedTime() + " ms");

    if (ti.isSuspended()) {
        sb.append(" (suspended)");
    }
    if (ti.isInNative()) {
        sb.append(" (running in native)");
    }
    sb.append(CRLF);
    sb.append(INDENT3 + "java.lang.Thread.State: " + ti.getThreadState());
    sb.append(CRLF);
    return sb.toString();
}
 
Example 22
Project: dremio-oss   File: ThreadsIterator.java   Source Code and License 6 votes vote down vote up
@Override
public Object next() {
  ThreadInfo currentThread = threadInfoIterator.next();
  final NodeEndpoint endpoint = dbContext.getEndpoint();
  final long id = currentThread.getThreadId();
  return new ThreadSummary(endpoint.getAddress(),
          endpoint.getFabricPort(),
          currentThread.getThreadName(),
          currentThread.getThreadId(),
          currentThread.isInNative(),
          currentThread.isSuspended(),
          currentThread.getThreadState().name(),
          stats.getCpuTrailingAverage(id, 1),
          stats.getUserTrailingAverage(id, 1),
          NUMBER_OF_CORES,
          getStackTrace(currentThread));
}
 
Example 23
Project: openjdk-jdk10   File: LogManagerAppContextDeadlock.java   Source Code and License 6 votes vote down vote up
public void loop() {
    while(goOn) {
        try {
            long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
            ids = ids == null ? new long[0] : ids;
            if (ids.length == 1) {
                throw new RuntimeException("Found 1 deadlocked thread: "+ids[0]);
            } else if (ids.length > 0) {
                ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE);
                System.err.println("Found "+ids.length+" deadlocked threads: ");
                for (ThreadInfo inf : infos) {
                    System.err.println(inf);
                }
                throw new DeadlockException("Found "+ids.length+" deadlocked threads");
            }
            Thread.sleep(100);
        } catch(InterruptedException | RuntimeException x) {
            fail(x);
        }
    }
}
 
Example 24
Project: gate-core   File: ThreadWarningSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Monitor only deadlocks.
 */
public ThreadWarningSystem() {
  threadCheck.schedule(new TimerTask() {
    @Override
    public void run() {
      long[] ids = mbean.findMonitorDeadlockedThreads();
      if (ids != null && ids.length > 0) {
        for (Long l : ids) {
          if (!deadlockedThreads.contains(l)) {
            deadlockedThreads.add(l);
            ThreadInfo ti = mbean.getThreadInfo(l, MAX_STACK_DEPTH);
            fireDeadlockDetected(ti);
          }
        }
      }
    }
  }, 10, DEADLOCK_CHECK_PERIOD);
}
 
Example 25
Project: convertigo-engine   File: ThreadManager.java   Source Code and License 6 votes vote down vote up
private String getThreadInfo(ThreadInfo ti) {
	String message = "\"" + ti.getThreadName() + "\" [ID=" + ti.getThreadId() + "]";
	message += " is " + ti.getThreadState();
	
	if (ti.isSuspended()) {
		message += " (suspended)";
	}
	
	if (ti.isInNative()) {
		message += " (running in native)";
	}

	message += ":\n";
	
	if (ti.getLockName() != null) {
		message += INDENT + "waiting to lock " + ti.getLockName() + "\n";
	}
	
	if (ti.getLockOwnerName() != null) {
		message += INDENT + "owned by \"" + ti.getLockOwnerName() + "\" [ID=" + ti.getLockOwnerId() + "]\n";
	}
	
	return message;
}
 
Example 26
Project: openjdk-jdk10   File: TestLoggerBundleSync.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    while(goOn) {
        try {
            long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
            checkCount.incrementAndGet();
            ids = ids == null ? new long[0] : ids;
            if (ids.length == 1) {
                throw new RuntimeException("Found 1 deadlocked thread: "+ids[0]);
            } else if (ids.length > 0) {
                ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(ids);
                System.err.println("Found "+ids.length+" deadlocked threads: ");
                for (ThreadInfo inf : infos) {
                    System.err.println(inf.toString());
                }
                throw new RuntimeException("Found "+ids.length+" deadlocked threads");
            }
            Thread.sleep(100);
        } catch(InterruptedException | RuntimeException x) {
            fail(x);
        }
    }
}
 
Example 27
Project: OpenJSharp   File: JvmThreadInstanceEntryImpl.java   Source Code and License 6 votes vote down vote up
public static Byte[] getState(ThreadInfo info) {
    byte[] bitmap = new byte[] {(byte)0x00, (byte)0x00};
    try {
        final Thread.State state = info.getThreadState();
        final boolean inNative  = info.isInNative();
        final boolean suspended = info.isSuspended();
        log.debug("getJvmThreadInstState",
                  "[State=" + state +
                  ",isInNative=" + inNative +
                  ",isSuspended=" + suspended + "]");
        setState(bitmap,state);
        if (inNative)  setNative(bitmap);
        if (suspended) setSuspended(bitmap);
        checkOther(bitmap);
    } catch (RuntimeException r) {
        bitmap[0]=(byte)0x00;
        bitmap[1]=Byte1.other;
        log.trace("getJvmThreadInstState",
                  "Unexpected exception: " + r);
        log.debug("getJvmThreadInstState",r);
    }
    Byte[] result = { new Byte(bitmap[0]), new Byte(bitmap[1]) };
    return result;
}
 
Example 28
Project: jdk8u-jdk   File: TestLogConfigurationDeadLockWithConf.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    while(goOn) {
        try {
            long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
            checkCount.incrementAndGet();
            ids = ids == null ? new long[0] : ids;
            if (ids.length > 0) {
                deadlocked.addAll(asList(ids));
            }
            if (ids.length == 1) {
                throw new RuntimeException("Found 1 deadlocked thread: "+ids[0]);
            } else if (ids.length > 0) {
                ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE);
                System.err.println("Found "+ids.length+" deadlocked threads: ");
                for (ThreadInfo inf : infos) {
                    System.err.println(inf.toString());
                }
                throw new RuntimeException("Found "+ids.length+" deadlocked threads");
            }
            Thread.sleep(100);
        } catch(InterruptedException | RuntimeException x) {
            fail(x);
        }
    }
}
 
Example 29
Project: yacy_grid_mcp   File: ThreaddumpService.java   Source Code and License 5 votes vote down vote up
private ThreadDump(
        final Map<Thread, StackTraceElement[]> stackTraces,
        final Thread.State stateIn) {
    super();

    Thread thread;
    // collect single dumps
    for (final Map.Entry<Thread, StackTraceElement[]> entry: stackTraces.entrySet()) {
        thread = entry.getKey();
        final StackTraceElement[] stackTraceElements = entry.getValue();
        StackTraceElement ste;
        String tracename = "";
        final State threadState = thread.getState();
        final ThreadInfo info = Memory.threadBean.getThreadInfo(thread.getId());
        if (threadState != null && info != null && (stateIn == null || stateIn.equals(threadState)) && stackTraceElements.length > 0) {
            final StringBuilder sb = new StringBuilder(3000);
            final String threadtitle = tracename + "THREAD: " + thread.getName() + " " + (thread.isDaemon()?"daemon":"") + " id=" + thread.getId() + " " + threadState.toString() + (info.getLockOwnerId() >= 0 ? " lock owner =" + info.getLockOwnerId() : "");
            boolean cutcore = true;
            for (int i = 0; i < stackTraceElements.length; i++) {
                ste = stackTraceElements[i];
                String className = ste.getClassName();
                String classString = ste.toString();
                if (cutcore && (className.startsWith("java.") || className.startsWith("sun."))) {
                    sb.setLength(0);
                    bufferappend(sb, tracename + "at " + classString);
                } else {
                    cutcore = false;
                    bufferappend(sb, tracename + "at " + classString);
                }
            }
            final StackTrace stackTrace = new StackTrace(sb.toString());
            SortedSet<String> threads = get(stackTrace);
            if (threads == null) {
                threads = new TreeSet<String>();
                put(stackTrace, threads);
            }
            threads.add(threadtitle);
        }
    }
}
 
Example 30
Project: yacy_grid_mcp   File: Memory.java   Source Code and License 5 votes vote down vote up
/**
 * write deadlocked threads as to the log as warning
 */
public static void logDeadlocks() {
    long[] deadlockIDs = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
    if (deadlockIDs == null) return;
    ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(deadlockIDs, true, true);
    for (ThreadInfo ti : infos) {
        Data.logger.warn("DEADLOCKREPORT: " + ti.toString());
    }
}
 
Example 31
Project: Nukkit-Java9   File: Utils.java   Source Code and License 5 votes vote down vote up
public static String getAllThreadDumps() {
    ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
    StringBuilder builder = new StringBuilder();
    for (ThreadInfo info : threads) {
        builder.append('\n').append(info);
    }
    return builder.toString();
}
 
Example 32
Project: incubator-netbeans   File: NbTestCase.java   Source Code and License 5 votes vote down vote up
private static void printMonitorInfo(ThreadInfo ti, MonitorInfo[] monitors, StringBuilder sb) {
    sb.append("\tLocked monitors: count = " + monitors.length).append("\n");
    for (MonitorInfo mi : monitors) {
        sb.append("\t  - " + mi + " locked at ").append("\n");
        sb.append("\t      " + mi.getLockedStackDepth() + " "
                + mi.getLockedStackFrame()).append("\n");
    }
}
 
Example 33
Project: lazycat   File: Diagnostics.java   Source Code and License 5 votes vote down vote up
/**
 * Formats the thread dump for a list of threads.
 *
 * @param tinfos
 *            the ThreadInfo array describing the thread list
 * @return the formatted thread dump
 */
private static String getThreadDump(ThreadInfo[] tinfos) {
	StringBuilder sb = new StringBuilder();
	for (ThreadInfo tinfo : tinfos) {
		sb.append(getThreadDump(tinfo));
		sb.append(CRLF);
	}
	return sb.toString();
}
 
Example 34
Project: jdk8u-jdk   File: TestThread.java   Source Code and License 5 votes vote down vote up
/**
 * Waits until {@link TestThread} is in native.
 */
public void waitUntilInNative() {
    ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
    while (isAlive()) {
        ThreadInfo ti = tmx.getThreadInfo(getId());
        if (ti.isInNative()) {
            return;
        }
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }
}
 
Example 35
Project: jdk8u-jdk   File: ThreadInfoCompositeData.java   Source Code and License 5 votes vote down vote up
public static void createGoodCompositeData() throws Exception {
     CompositeType ct =
         new CompositeType("MyCompositeType",
                           "CompositeType for ThreadInfo",
                           validItemNames,
                           validItemNames,
                           validItemTypes);
     CompositeData cd =
         new CompositeDataSupport(ct,
                                  validItemNames,
                                  values);
     ThreadInfo info = ThreadInfo.from(cd);
     checkThreadInfo(info);
}
 
Example 36
Project: incubator-netbeans   File: SampledCPUSnapshot.java   Source Code and License 5 votes vote down vote up
public long getValue(int sampleIndex, int valIndex) throws IOException {
    getSample(sampleIndex);
    long ret = 0;
    for (ThreadInfo info : sample.getTinfos()) {
        if (info.getThreadState().equals(Thread.State.RUNNABLE)) {
            ret += info.getStackTrace().length;
        }
    }
    return ret;
}
 
Example 37
Project: openjdk-jdk10   File: ThreadMXBeanTool.java   Source Code and License 5 votes vote down vote up
/**
 * Waits until {@link Thread} is in native.
 */
public static void waitUntilInNative(Thread thread) throws InterruptedException {
    ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
    while (thread.isAlive()) {
        ThreadInfo ti = tmx.getThreadInfo(thread.getId());
        if (ti.isInNative()) {
            return;
        }
        Thread.sleep(1);
    }
}
 
Example 38
Project: openjdk-jdk10   File: JSR166TestCase.java   Source Code and License 5 votes vote down vote up
/**
 * A debugging tool to print stack traces of most threads, as jstack does.
 * Uninteresting threads are filtered out.
 */
static void dumpTestThreads() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        try {
            System.setSecurityManager(null);
        } catch (SecurityException giveUp) {
            return;
        }
    }

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    System.err.println("------ stacktrace dump start ------");
    for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
        final String name = info.getThreadName();
        String lockName;
        if ("Signal Dispatcher".equals(name))
            continue;
        if ("Reference Handler".equals(name)
            && (lockName = info.getLockName()) != null
            && lockName.startsWith("java.lang.ref.Reference$Lock"))
            continue;
        if ("Finalizer".equals(name)
            && (lockName = info.getLockName()) != null
            && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
            continue;
        if ("checkForWedgedTest".equals(name))
            continue;
        System.err.print(info);
    }
    System.err.println("------ stacktrace dump end ------");

    if (sm != null) System.setSecurityManager(sm);
}
 
Example 39
Project: incubator-netbeans   File: ThreadDump.java   Source Code and License 5 votes vote down vote up
public ThreadInfo[] getThreads() {
    synchronized (tinfoLock) {
        if (tinfos == null) {
            int i = 0;
            tinfos = new ThreadInfo[cdThreads.length];
            for (Object cd : cdThreads) {
                tinfos[i++] = ThreadInfo.from((CompositeData) cd);
            }
            cdThreads = null;
        }
        return tinfos;
    }
}
 
Example 40
Project: jdk8u-jdk   File: ThreadImpl.java   Source Code and License 5 votes vote down vote up
public ThreadInfo[] getThreadInfo(long[] ids,
                                  boolean lockedMonitors,
                                  boolean lockedSynchronizers) {
    verifyThreadIds(ids);
    // ids has been verified to be non-null
    // an empty array of ids should return an empty array of ThreadInfos
    if (ids.length == 0) return new ThreadInfo[0];

    verifyDumpThreads(lockedMonitors, lockedSynchronizers);
    return dumpThreads0(ids, lockedMonitors, lockedSynchronizers);
}
 
Example 41
Project: incubator-netbeans   File: StackTraceSnapshotBuilderTest.java   Source Code and License 5 votes vote down vote up
private void addStacktrace(java.lang.management.ThreadInfo[] tinfos, long time) {
    java.lang.management.ThreadInfo[] newInfo = new java.lang.management.ThreadInfo[tinfos.length];
    int i = 0;

    for (java.lang.management.ThreadInfo tinfo : tinfos) {
        CompositeData aaa = ThreadInfoCompositeData.toCompositeData(tinfo);
        newInfo[i++] = ThreadInfo.from(aaa);
    }
    instance.addStacktrace(newInfo, time);
}
 
Example 42
Project: monarch   File: LocalThread.java   Source Code and License 5 votes vote down vote up
private String generateThreadStack(ThreadInfo info) {
  // This is annoying, but the to string method on info sucks.
  StringBuilder result = new StringBuilder();
  result.append(info.getThreadName()).append(" ID=0x")
      .append(Long.toHexString(info.getThreadId())).append("(").append(info.getThreadId())
      .append(") state=").append(info.getThreadState());


  if (info.getLockInfo() != null) {
    result.append("\n\twaiting to lock <" + info.getLockInfo() + ">");
  }
  for (StackTraceElement element : info.getStackTrace()) {
    result.append("\n\tat " + element);
    for (MonitorInfo monitor : info.getLockedMonitors()) {
      if (element.equals(monitor.getLockedStackFrame())) {
        result.append("\n\tlocked <" + monitor + ">");
      }
    }
  }

  if (info.getLockedSynchronizers().length > 0) {
    result.append("\nLocked synchronizers:");
    for (LockInfo sync : info.getLockedSynchronizers()) {
      result.append(
          "\n" + sync.getClassName() + "@" + Integer.toHexString(sync.getIdentityHashCode()));

    }
  }

  return result.toString();
}
 
Example 43
Project: OpenJSharp   File: ThreadMonitor.java   Source Code and License 5 votes vote down vote up
private void printMonitorInfo(ThreadInfo ti) {
   MonitorInfo[] monitors = ti.getLockedMonitors();
   System.out.println(INDENT + "Locked monitors: count = " + monitors.length);
   for (MonitorInfo mi : monitors) {
       System.out.println(INDENT + "  - " + mi + " locked at ");
       System.out.println(INDENT + "      " + mi.getLockedStackDepth() +
                          " " + mi.getLockedStackFrame());
   }
}
 
Example 44
Project: jdk8u-jdk   File: MappedMXBeanType.java   Source Code and License 5 votes vote down vote up
Object toOpenTypeData(Object data) throws OpenDataException {
    if (data instanceof MemoryUsage) {
        return MemoryUsageCompositeData.toCompositeData((MemoryUsage) data);
    }

    if (data instanceof ThreadInfo) {
        return ThreadInfoCompositeData.toCompositeData((ThreadInfo) data);
    }

    if (data instanceof LockInfo) {
        if (data instanceof java.lang.management.MonitorInfo) {
            return MonitorInfoCompositeData.toCompositeData((MonitorInfo) data);
        }
        return LockInfoCompositeData.toCompositeData((LockInfo) data);
    }

    if (data instanceof MemoryNotificationInfo) {
        return MemoryNotifInfoCompositeData.
            toCompositeData((MemoryNotificationInfo) data);
    }

    if (data instanceof VMOption) {
        return VMOptionCompositeData.toCompositeData((VMOption) data);
    }

    if (isCompositeData) {
        // Classes that implement CompositeData
        //
        // construct a new CompositeDataSupport object
        // so that no other classes are sent over the wire
        CompositeData cd = (CompositeData) data;
        CompositeType ct = cd.getCompositeType();
        String[] itemNames = ct.keySet().toArray(new String[0]);
        Object[] itemValues = cd.getAll(itemNames);
        return new CompositeDataSupport(ct, itemNames, itemValues);
    }

    throw new OpenDataException(javaClass.getName() +
        " is not supported for platform MXBeans");
}
 
Example 45
Project: elasticsearch_my   File: LongGCDisruption.java   Source Code and License 5 votes vote down vote up
protected void onBlockDetected(ThreadInfo blockedThread, @Nullable ThreadInfo blockingThread) {
    String blockedThreadStackTrace = stackTrace(blockedThread.getStackTrace());
    String blockingThreadStackTrace = blockingThread != null ?
        stackTrace(blockingThread.getStackTrace()) : "not available";
    throw new AssertionError("Thread [" + blockedThread.getThreadName() + "] is blocked waiting on the resource [" +
        blockedThread.getLockInfo() + "] held by the suspended thread [" + blockedThread.getLockOwnerName() +
        "] of the disrupted node [" + disruptedNode + "].\n" +
        "Please add this occurrence to the unsafeClasses list in [" + LongGCDisruption.class.getName() + "].\n" +
        "Stack trace of blocked thread: " + blockedThreadStackTrace + "\n" +
        "Stack trace of blocking thread: " + blockingThreadStackTrace);
}
 
Example 46
Project: elasticsearch_my   File: DeadlockAnalyzer.java   Source Code and License 5 votes vote down vote up
private Deadlock[] createDeadlockDescriptions(Set<LinkedHashSet<ThreadInfo>> cycles) {
    Deadlock result[] = new Deadlock[cycles.size()];
    int count = 0;
    for (LinkedHashSet<ThreadInfo> cycle : cycles) {
        ThreadInfo asArray[] = cycle.toArray(new ThreadInfo[cycle.size()]);
        Deadlock d = new Deadlock(asArray);
        result[count++] = d;
    }
    return result;
}
 
Example 47
Project: java-performance   File: ThreadSampler.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {
    while (!isInterrupted()) {
        ThreadMXBean threadMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
        System.out.println(">>>>>>>>>>> Dumping threads");
        ThreadInfo[] info = threadMXBean.dumpAllThreads(true, true);
        System.out.println(Arrays.toString(info));

        delaySleep();
    }

    System.out.println("ThreadSampler stopped");
}
 
Example 48
Project: lazycat   File: Diagnostics.java   Source Code and License 5 votes vote down vote up
/**
 * Check if any threads are deadlocked. If any, print the thread dump for
 * those threads.
 *
 * @return a deadlock message and the formatted thread dump of the
 *         deadlocked threads
 */
private static String findDeadlock() {
	ThreadInfo[] tinfos = null;
	long[] ids = threadMXBean.findDeadlockedThreads();
	if (ids != null) {
		tinfos = threadMXBean.getThreadInfo(threadMXBean.findDeadlockedThreads(), true, true);
		if (tinfos != null) {
			StringBuilder sb = new StringBuilder("Deadlock found between the following threads:");
			sb.append(CRLF);
			sb.append(getThreadDump(tinfos));
			return sb.toString();
		}
	}
	return "";
}
 
Example 49
Project: Elasticsearch   File: HotThreads.java   Source Code and License 5 votes vote down vote up
void setDelta(long cpuTime, ThreadInfo info) {
    if (deltaDone) throw new IllegalStateException("setDelta already called once");
    blockedCount = info.getBlockedCount() - blockedCount;
    blockedTime = info.getBlockedTime() - blockedTime;
    waitedCount = info.getWaitedCount() - waitedCount;
    waitedTime = info.getWaitedTime() - waitedTime;
    this.cpuTime = cpuTime - this.cpuTime;
    deltaDone = true;
    this.info = info;
}
 
Example 50
Project: elasticsearch_my   File: HotThreads.java   Source Code and License 5 votes vote down vote up
private int similarity(ThreadInfo threadInfo, ThreadInfo threadInfo0) {
    StackTraceElement[] s1 = threadInfo == null ? EMPTY : threadInfo.getStackTrace();
    StackTraceElement[] s2 = threadInfo0 == null ? EMPTY : threadInfo0.getStackTrace();
    int i = s1.length - 1;
    int j = s2.length - 1;
    int rslt = 0;
    while (i >= 0 && j >= 0 && s1[i].equals(s2[j])) {
        rslt++;
        i--;
        j--;
    }
    return rslt;
}
 
Example 51
Project: elasticsearch_my   File: HotThreads.java   Source Code and License 5 votes vote down vote up
MyThreadInfo(long cpuTime, ThreadInfo info) {
    blockedCount = info.getBlockedCount();
    blockedTime = info.getBlockedTime();
    waitedCount = info.getWaitedCount();
    waitedTime = info.getWaitedTime();
    this.cpuTime = cpuTime;
    this.info = info;
}
 
Example 52
Project: jdk8u-jdk   File: ThreadMonitor.java   Source Code and License 5 votes vote down vote up
/**
 * Prints the thread dump information with locks info to System.out.
 */
private void dumpThreadInfoWithLocks() {
   System.out.println("Full Java thread dump with locks info");

   ThreadInfo[] tinfos = tmbean.dumpAllThreads(true, true);
   for (ThreadInfo ti : tinfos) {
       printThreadInfo(ti);
       LockInfo[] syncs = ti.getLockedSynchronizers();
       printLockInfo(syncs);
   }
   System.out.println();
}
 
Example 53
Project: NoMoreOversleeps   File: DebugHandler.java   Source Code and License 5 votes vote down vote up
/** Returns an array list of debug information for all Java threads; useful for trying to diagnose the cause of odd behaviour.
 * 
 * @return An array list of debug information
 */
public static ArrayList<String> getThreadDebugData()
{
	ArrayList<String> strings = new ArrayList<String>();

	strings.add("------------------------------------------------------------");
	strings.add("Debugging information for Java virtual machine");
	ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
	for (ThreadInfo thread : threads)
	{
		if (thread.getThreadState() != State.WAITING)
		{
			strings.add("------------------------------------------------------------");
			strings.add(thread.getThreadName());
			strings.add("\tPID: " + thread.getThreadId() + " | Suspended: " + thread.isSuspended() + " | Native: " + thread.isInNative() + " | State: " + thread.getThreadState());
			if (thread.getLockedMonitors().length != 0)
			{
				strings.add("\tThread is waiting on monitor(s):");
				for (MonitorInfo monitor : thread.getLockedMonitors())
				{
					strings.add("\t\tLocked on:" + monitor.getLockedStackFrame());
				}
			}
			strings.add("\tStack trace:");

			StackTraceElement[] stack = thread.getStackTrace();
			for (int line = 0; line < stack.length; line++)
			{
				strings.add("\t\t" + stack[line].toString());
			}
		}
	}
	strings.add("------------------------------------------------------------");
	strings.add("End of debugging information");
	strings.add("------------------------------------------------------------");

	return strings;
}
 
Example 54
Project: OpenJSharp   File: ThreadImpl.java   Source Code and License 5 votes vote down vote up
public ThreadInfo[] getThreadInfo(long[] ids,
                                  boolean lockedMonitors,
                                  boolean lockedSynchronizers) {
    verifyThreadIds(ids);
    verifyDumpThreads(lockedMonitors, lockedSynchronizers);
    return dumpThreads0(ids, lockedMonitors, lockedSynchronizers);
}
 
Example 55
Project: OpenJSharp   File: ThreadMonitor.java   Source Code and License 5 votes vote down vote up
/**
 * Prints the thread dump information with locks info to System.out.
 */
private void dumpThreadInfoWithLocks() {
   System.out.println("Full Java thread dump with locks info");

   ThreadInfo[] tinfos = tmbean.dumpAllThreads(true, true);
   for (ThreadInfo ti : tinfos) {
       printThreadInfo(ti);
       LockInfo[] syncs = ti.getLockedSynchronizers();
       printLockInfo(syncs);
   }
   System.out.println();
}
 
Example 56
Project: tomcat7   File: Diagnostics.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieve a JVM thread dump formatted
 * using the given StringManager.
 *
 * @param requestedSm the StringManager to use
 * @return the formatted JVM thread dump
 */
private static String getThreadDump(StringManager requestedSm) {
    StringBuilder sb = new StringBuilder();

    synchronized(timeformat) {
        sb.append(timeformat.format(new Date()));
    }
    sb.append(CRLF);

    sb.append(requestedSm.getString("diagnostics.threadDumpTitle"));
    sb.append(" ");
    sb.append(runtimeMXBean.getVmName());
    sb.append(" (");
    sb.append(runtimeMXBean.getVmVersion());
    String vminfo = System.getProperty(vminfoSystemProperty);
    if (vminfo != null) {
        sb.append(" " + vminfo);
    }
    sb.append("):" + CRLF);
    sb.append(CRLF);

    ThreadInfo[] tis = threadMXBean.dumpAllThreads(true, true);
    sb.append(getThreadDump(tis));

    sb.append(findDeadlock());
    return sb.toString();
}
 
Example 57
Project: ditb   File: GenericTestUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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()));
    }
  }
}
 
Example 58
Project: jdk8u-jdk   File: DrainFindDeadlockTest.java   Source Code and License 5 votes vote down vote up
void checkState(Thread x, Thread y) {
    //            System.out.println("checkstate");
    boolean isXblocked = x.getState().equals(State.BLOCKED);
    boolean isYblocked = y.getState().equals(State.BLOCKED);
    long[] deadlockedThreads = null;

    if (isXblocked && isYblocked) {
        System.out.println("threads blocked");
        // they are both blocked, but this doesn't necessarily mean
        // they are deadlocked
        if (threadMXBeanDeadlockSupported) {
            System.out.println("checking for deadlock");
            deadlockedThreads = threadMXBean.findDeadlockedThreads();
        } else {
            System.out.println("Can't check for deadlock");
        }
        if (deadlockedThreads != null) {
            System.out.println("We detected a deadlock! ");
            ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(
                    deadlockedThreads, true, true);
            for (ThreadInfo threadInfo: threadInfos) {
                System.out.println(threadInfo);
            }
            throw new RuntimeException("TEST FAILED: Deadlock detected");
        }
        System.out.println("We may have a deadlock");
        Map<Thread, StackTraceElement[]> threadMap =
                Thread.getAllStackTraces();
        dumpStack(threadMap.get(x), x);
        dumpStack(threadMap.get(y), y);
    }
}
 
Example 59
Project: gate-core   File: Main.java   Source Code and License 5 votes vote down vote up
/** Main routine for GATE.
  * Command-line arguments:
  * <UL>
  * <LI>
  * <B>-h</B> display a short help message
  * <LI>
  * <B>-d URL</B> define URL to be a location for CREOLE resoures
  * <LI>
  * <B>-i file</B> additional initialisation file (probably called
  *   <TT>gate.xml</TT>). Used for site-wide initialisation by the
  *   start-up scripts
  * </UL>
  */
public static void main(String[] args) throws GateException {
  
  // check we have a useable JDK
  if(
    System.getProperty("java.version").compareTo(Gate.getMinJdkVersion())
    < 0
  ) {
    throw new GateException(
      "GATE requires JDK " + Gate.getMinJdkVersion() + " or newer"
    );
  }
  
  ThreadWarningSystem tws = new ThreadWarningSystem();
  tws.addListener(new ThreadWarningSystem.Listener() {
    
    final PrintStream out = System.out;
    
    @Override
    public void deadlockDetected(ThreadInfo inf) {
      out.println("Deadlocked Thread:");
      out.println("------------------");
      out.println(inf);
      for (StackTraceElement ste : inf.getStackTrace()) {
        out.println("\t" + ste);
      }
    }
    @Override
    public void thresholdExceeded(ThreadInfo[] threads) { }
  });

  // process command-line options
  processArgs(args);
  
  runGui();
}
 
Example 60
Project: gate-core   File: ThreadWarningSystem.java   Source Code and License 5 votes vote down vote up
private void fireDeadlockDetected(ThreadInfo thread) {
  // In general I avoid using synchronized.  The surrounding
  // code should usually be responsible for being threadsafe.
  // However, in this case, the timer could be notifying at
  // the same time as someone is adding a listener, and there
  // is nothing the calling code can do to prevent that from
  // occurring.  Another tip though is this: when I synchronize
  // I use a private field to synchronize on, instead of
  // "this".
  synchronized (listeners) {
    for (Listener l : listeners) {
      l.deadlockDetected(thread);
    }
  }
}