@Override public void query(QueryContext context, String queryString, MetadataCallback callback) { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); ArrayList<ThreadCpuUsage> usages = new ArrayList<ThreadCpuUsage>(); for (long tid : bean.getAllThreadIds()) { long time = bean.getThreadCpuTime(tid); usages.add(new ThreadCpuUsage(tid, time)); } try { Thread.sleep(1000); } catch (InterruptedException e) { } Map<Thread, StackTraceElement[]> stacks = Thread.getAllStackTraces(); for (long tid : bean.getAllThreadIds()) { ThreadCpuUsage usage = find(usages, tid); if (usage != null) usage.secondTime = bean.getThreadCpuTime(tid); } Collections.sort(usages); for (ThreadCpuUsage usage : usages) { long elapsed = usage.secondTime - usage.firstTime; // remove just created thread or sleeping threads (noisy) if (elapsed <= 0) continue; StringBuilder sb = new StringBuilder(); Thread t = findThread(stacks, usage.tid); if (t == null) continue; StackTraceElement[] stack = findStack(stacks, usage.tid); for (StackTraceElement el : stack) { sb.append( String.format( "%s.%s %s\n", el.getClassName(), el.getMethodName(), getFileAndLineNumber(el))); } Map<String, Object> m = new HashMap<String, Object>(); m.put("tid", t.getId()); m.put("name", t.getName()); m.put("state", t.getState().toString()); m.put("priority", t.getPriority()); m.put("usage", elapsed); m.put("stacktrace", sb.toString()); callback.onPush(new Row(m)); } }
/** * Update the information about completed thread that ran for runtime in milliseconds * * <p>This method updates all of the key timing and tracking information in the factory so that * thread can be retired. After this call the factory shouldn't have a pointer to the thread any * longer * * @param thread the thread whose information we are updating */ @Ensures({"getTotalTime() >= old(getTotalTime())"}) public synchronized void threadIsDone(final Thread thread) { nThreadsAnalyzed++; if (DEBUG) logger.warn("UpdateThreadInfo called"); final long threadID = thread.getId(); final ThreadInfo info = bean.getThreadInfo(thread.getId()); final long totalTimeNano = bean.getThreadCpuTime(threadID); final long userTimeNano = bean.getThreadUserTime(threadID); final long systemTimeNano = totalTimeNano - userTimeNano; final long userTimeInMilliseconds = nanoToMilli(userTimeNano); final long systemTimeInMilliseconds = nanoToMilli(systemTimeNano); if (info != null) { if (DEBUG) logger.warn( "Updating thread with user runtime " + userTimeInMilliseconds + " and system runtime " + systemTimeInMilliseconds + " of which blocked " + info.getBlockedTime() + " and waiting " + info.getWaitedTime()); incTimes(State.BLOCKING, info.getBlockedTime()); incTimes(State.WAITING, info.getWaitedTime()); incTimes(State.USER_CPU, userTimeInMilliseconds); incTimes(State.WAITING_FOR_IO, systemTimeInMilliseconds); } }
public boolean search() { Thread tread = java.lang.Thread.currentThread(); java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean(); long startCPU = b.getThreadCpuTime(tread.getId()); long startUser = b.getThreadUserTime(tread.getId()); boolean result = store.consistency(); System.out.println("*** consistency = " + result); Search<SetVar> label = new DepthFirstSearch<SetVar>(); SelectChoicePoint<SetVar> select = new SimpleSelect<SetVar>( vars.toArray(new SetVar[vars.size()]), new MinLubCard<SetVar>(), new MaxGlbCard<SetVar>(), new IndomainSetMin<SetVar>()); // label.setSolutionListener(new SetSimpleSolutionListener<SetVar>()); label.getSolutionListener().searchAll(false); label.getSolutionListener().recordSolutions(false); result = label.labeling(store, select); if (result) { System.out.println("*** Yes"); for (int i = 0; i < weeks; i++) { for (int j = 0; j < groups; j++) { System.out.print(golferGroup[i][j].dom() + " "); } System.out.println(); } } else System.out.println("*** No"); System.out.println( "ThreadCpuTime = " + (b.getThreadCpuTime(tread.getId()) - startCPU) / (long) 1e+6 + "ms"); System.out.println( "ThreadUserTime = " + (b.getThreadUserTime(tread.getId()) - startUser) / (long) 1e+6 + "ms"); return result; }
/** * It parses the provided file and parsing parameters followed by problem solving. * * @param args parameters describing the flatzinc file containing the problem to be solved as well * as options for problem solving. * <p>TODO what are the conditions for different exceptions being thrown? Write little info * below. * @throws ParseException * @throws TokenMgrError */ public static void main(String[] args) { Options opt = new Options(args); if (opt.getVerbose()) System.out.println("Flatzinc2JaCoP: compiling and executing " + args[args.length - 1]); Thread tread = java.lang.Thread.currentThread(); java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean(); long startCPU = b.getThreadCpuTime(tread.getId()); Parser parser = new Parser(opt.getFile()); parser.setOptions(opt); try { parser.model(); } catch (FailException e) { System.err.println( "=====UNSATISFIABLE====="); // "*** Evaluation of model resulted in fail."); } catch (ArithmeticException e) { System.err.println("*** Evaluation of model resulted in integer overflow."); } catch (ParseException e) { System.out.println("*** Parser exception " + e); } catch (TokenMgrError e) { System.out.println("*** Parser exception " + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("*** Array out of bound exception " + e); } catch (OutOfMemoryError e) { System.out.println("*** Out of memory error; consider option -Xmx... for JVM"); } catch (StackOverflowError e) { System.out.println("*** Stack overflow exception error; consider option -Xss... for JVM"); } if (opt.getStatistics()) { System.out.println( "\nTotal CPU time : " + (b.getThreadCpuTime(tread.getId()) - startCPU) / (long) 1e+6 + "ms"); } }
@DwrPermission(admin = true) public ProcessResult getThreadInfo() { synchronized (threadInfos) { ProcessResult result = new ProcessResult(); // All of the last thread ids. Ids are removed from this set as they are processed. If ids // remain, // it means the thread is gone and should be removed from the map. Set<Long> threadIds = new HashSet<>(threadInfos.keySet()); ThreadInfo[] threads = tmxb.getThreadInfo(tmxb.getAllThreadIds(), Integer.MAX_VALUE); List<ThreadInfoBean> beans = new ArrayList<>(); for (ThreadInfo thread : threads) { if (thread == null) continue; ThreadInfoBean bean = threadInfos.get(thread.getThreadId()); if (bean == null) { bean = new ThreadInfoBean(); bean.setId(thread.getThreadId()); bean.setName(thread.getThreadName()); threadInfos.put(bean.getId(), bean); } else threadIds.remove(bean.getId()); bean.setCpuTime(tmxb.getThreadCpuTime(bean.getId())); bean.setState(thread.getThreadState().name()); if (thread.getThreadState() == State.BLOCKED) bean.setState( bean.getState() + " by '" + thread.getLockOwnerName() + "' (" + thread.getLockOwnerId() + ")"); bean.setStackTrace(thread.getStackTrace()); beans.add(bean); } // Remove unreferenced threads for (Long id : threadIds) threadInfos.remove(id); result.addData("threads", beans); return result; } }
/** * 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="******" 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(); }
@RequestMapping("/loadThreadInfo") @ResponseBody public JSONObject doLoadThreadInfo(HttpServletRequest request) { try { String app = request.getParameter("app"); ThreadMXBean tBean = JMConnManager.getThreadMBean(app); ThreadInfo[] allThreads = tBean.dumpAllThreads(false, false); JSONObject root = new JSONObject(); JSONArray detail = new JSONArray(); HashMap<State, Integer> state = new HashMap<Thread.State, Integer>(); for (ThreadInfo info : allThreads) { JSONObject th = new JSONObject(); long threadId = info.getThreadId(); long cpu = tBean.getThreadCpuTime(threadId); State tState = info.getThreadState(); th.put("id", threadId); th.put("state", tState); th.put("name", info.getThreadName()); th.put("cpu", TimeUnit.NANOSECONDS.toMillis(cpu)); detail.add(th); Integer vl = state.get(tState); if (vl == null) { state.put(tState, 0); } else { state.put(tState, vl + 1); } } root.put("state", state); root.put("detail", detail); root.put("total", tBean.getThreadCount()); root.put("time", System.currentTimeMillis()); root.put("deamon", tBean.getDaemonThreadCount()); return root; } catch (IOException e) { throw new RuntimeException(e); } }
protected String generateThreadDump() { StringBuilder dump = new StringBuilder(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true); long currentThreadId = Thread.currentThread().getId(); for (ThreadInfo threadInfo : threadInfos) { long threadId = threadInfo.getThreadId(); if (threadId == currentThreadId) { continue; } dump.append('"'); dump.append(threadInfo.getThreadName()); dump.append("\" "); Thread.State state = threadInfo.getThreadState(); dump.append("\n\tjava.lang.Thread.State: "); dump.append(state); if (threadInfo.getLockName() != null) { dump.append(", on lock=").append(threadInfo.getLockName()); } if (threadInfo.getLockOwnerName() != null) { dump.append(", owned by ").append(threadInfo.getLockOwnerName()); dump.append(", id=").append(threadInfo.getLockOwnerId()); } if (THREAD_CPU_TIME_INFO_AVAILABLE) { dump.append(", cpu=").append(threadMXBean.getThreadCpuTime(threadId)).append(" nsecs"); dump.append(", usr="******" nsecs"); } if (THREAD_CONTENTION_INFO_AVAILABLE) { dump.append(", blocked=").append(threadInfo.getBlockedTime()).append(" msecs"); dump.append(", waited=").append(threadInfo.getWaitedTime()).append(" msecs"); } StackTraceElement[] stackTraceElements = threadInfo.getStackTrace(); for (StackTraceElement stackTraceElement : stackTraceElements) { dump.append("\n\t\tat "); dump.append(stackTraceElement); } dump.append("\n\n"); } return dump.toString(); }
/** * Return current (raw) list of thread info objects wrapped in ThreadRankInfo type. * * @return list of threads */ protected List<ThreadRankInfo> rawList() { // Platform MBean Server startup might be suspended (eg. for JBoss AS); if (threadMXBean == null) { if (mBeanServerRegistry.lookup("java") != null) { threadMXBean = ManagementFactory.getThreadMXBean(); } else { return new ArrayList<ThreadRankInfo>(1); } } ThreadInfo[] ati = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds()); List<ThreadRankInfo> lst = new ArrayList<ThreadRankInfo>(ati.length); for (ThreadInfo ti : ati) { long tid = ti.getThreadId(); long cpuTime = threadMXBean.getThreadCpuTime(tid); lst.add(new ThreadRankInfo(tid, ti.getThreadName(), cpuTime, ti.getBlockedTime())); } return lst; }
private static SimpleOrderedMap<Object> getThreadInfo(ThreadInfo ti, ThreadMXBean tmbean) { SimpleOrderedMap<Object> info = new SimpleOrderedMap<Object>(); long tid = ti.getThreadId(); info.add("id", tid); info.add("name", ti.getThreadName()); info.add("state", ti.getThreadState().toString()); if (ti.getLockName() != null) { info.add("lock", ti.getLockName()); } if (ti.isSuspended()) { info.add("suspended", true); } if (ti.isInNative()) { info.add("native", true); } if (tmbean.isThreadCpuTimeSupported()) { info.add("cpuTime", formatNanos(tmbean.getThreadCpuTime(tid))); info.add("userTime", formatNanos(tmbean.getThreadUserTime(tid))); } if (ti.getLockOwnerName() != null) { SimpleOrderedMap<Object> owner = new SimpleOrderedMap<Object>(); owner.add("name", ti.getLockOwnerName()); owner.add("id", ti.getLockOwnerId()); } // Add the stack trace int i = 0; String[] trace = new String[ti.getStackTrace().length]; for (StackTraceElement ste : ti.getStackTrace()) { trace[i++] = ste.toString(); } info.add("stackTrace", trace); return info; }
/** * @param thread * @return cpu time for the given thread in seconds, <code>-1</code> if cpu time is not measured. */ public static final double getThreadCpuTime(final Thread thread) { if (tbe.isThreadCpuTimeEnabled()) { return tbe.getThreadCpuTime(thread.getId()) / 1.0e9; } return -1; }
public static long getThreadTime(long tid) { ThreadMXBean tb = ManagementFactory.getThreadMXBean(); return tb.getThreadCpuTime(tid); }
private String innerDetect() throws Exception { StringBuilder sb = new StringBuilder(); sb.append("Hot threads at "); sb.append(DATE_TIME_FORMATTER.printer().print(System.currentTimeMillis())); sb.append(", interval="); sb.append(interval); sb.append(", busiestThreads="); sb.append(busiestThreads); sb.append(", ignoreIdleThreads="); sb.append(ignoreIdleThreads); sb.append(":\n"); ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); boolean enabledCpu = false; try { if (threadBean.isThreadCpuTimeSupported()) { if (!threadBean.isThreadCpuTimeEnabled()) { enabledCpu = true; threadBean.setThreadCpuTimeEnabled(true); } } else { throw new IllegalStateException("MBean doesn't support thread CPU Time"); } Map<Long, MyThreadInfo> threadInfos = new HashMap<>(); for (long threadId : threadBean.getAllThreadIds()) { // ignore our own thread... if (Thread.currentThread().getId() == threadId) { continue; } long cpu = threadBean.getThreadCpuTime(threadId); if (cpu == -1) { continue; } ThreadInfo info = threadBean.getThreadInfo(threadId, 0); if (info == null) { continue; } threadInfos.put(threadId, new MyThreadInfo(cpu, info)); } Thread.sleep(interval.millis()); for (long threadId : threadBean.getAllThreadIds()) { // ignore our own thread... if (Thread.currentThread().getId() == threadId) { continue; } long cpu = threadBean.getThreadCpuTime(threadId); if (cpu == -1) { threadInfos.remove(threadId); continue; } ThreadInfo info = threadBean.getThreadInfo(threadId, 0); if (info == null) { threadInfos.remove(threadId); continue; } MyThreadInfo data = threadInfos.get(threadId); if (data != null) { data.setDelta(cpu, info); } else { threadInfos.remove(threadId); } } // sort by delta CPU time on thread. List<MyThreadInfo> hotties = new ArrayList<>(threadInfos.values()); final int busiestThreads = Math.min(this.busiestThreads, hotties.size()); // skip that for now CollectionUtil.introSort( hotties, new Comparator<MyThreadInfo>() { @Override public int compare(MyThreadInfo o1, MyThreadInfo o2) { if ("cpu".equals(type)) { return (int) (o2.cpuTime - o1.cpuTime); } else if ("wait".equals(type)) { return (int) (o2.waitedTime - o1.waitedTime); } else if ("block".equals(type)) { return (int) (o2.blockedTime - o1.blockedTime); } throw new IllegalArgumentException(); } }); // analyse N stack traces for M busiest threads long[] ids = new long[busiestThreads]; for (int i = 0; i < busiestThreads; i++) { MyThreadInfo info = hotties.get(i); ids[i] = info.info.getThreadId(); } ThreadInfo[][] allInfos = new ThreadInfo[threadElementsSnapshotCount][]; for (int j = 0; j < threadElementsSnapshotCount; j++) { // NOTE, javadoc of getThreadInfo says: If a thread of the given ID is not alive or does not // exist, // null will be set in the corresponding element in the returned array. A thread is alive if // it has // been started and has not yet died. allInfos[j] = threadBean.getThreadInfo(ids, Integer.MAX_VALUE); Thread.sleep(threadElementsSnapshotDelay.millis()); } for (int t = 0; t < busiestThreads; t++) { long time = 0; if ("cpu".equals(type)) { time = hotties.get(t).cpuTime; } else if ("wait".equals(type)) { time = hotties.get(t).waitedTime; } else if ("block".equals(type)) { time = hotties.get(t).blockedTime; } String threadName = null; for (ThreadInfo[] info : allInfos) { if (info != null && info[t] != null) { if (ignoreIdleThreads && isIdleThread(info[t])) { info[t] = null; continue; } threadName = info[t].getThreadName(); break; } } if (threadName == null) { continue; // thread is not alive yet or died before the first snapshot - ignore it! } double percent = (((double) time) / interval.nanos()) * 100; sb.append( String.format( Locale.ROOT, "%n%4.1f%% (%s out of %s) %s usage by thread '%s'%n", percent, TimeValue.timeValueNanos(time), interval, type, threadName)); // for each snapshot (2nd array index) find later snapshot for same thread with max number // of // identical StackTraceElements (starting from end of each) boolean[] done = new boolean[threadElementsSnapshotCount]; for (int i = 0; i < threadElementsSnapshotCount; i++) { if (done[i]) continue; int maxSim = 1; boolean[] similars = new boolean[threadElementsSnapshotCount]; for (int j = i + 1; j < threadElementsSnapshotCount; j++) { if (done[j]) continue; int similarity = similarity(allInfos[i][t], allInfos[j][t]); if (similarity > maxSim) { maxSim = similarity; similars = new boolean[threadElementsSnapshotCount]; } if (similarity == maxSim) similars[j] = true; } // print out trace maxSim levels of i, and mark similar ones as done int count = 1; for (int j = i + 1; j < threadElementsSnapshotCount; j++) { if (similars[j]) { done[j] = true; count++; } } if (allInfos[i][t] != null) { final StackTraceElement[] show = allInfos[i][t].getStackTrace(); if (count == 1) { sb.append(String.format(Locale.ROOT, " unique snapshot%n")); for (int l = 0; l < show.length; l++) { sb.append(String.format(Locale.ROOT, " %s%n", show[l])); } } else { sb.append( String.format( Locale.ROOT, " %d/%d snapshots sharing following %d elements%n", count, threadElementsSnapshotCount, maxSim)); for (int l = show.length - maxSim; l < show.length; l++) { sb.append(String.format(Locale.ROOT, " %s%n", show[l])); } } } } } return sb.toString(); } finally { if (enabledCpu) { threadBean.setThreadCpuTimeEnabled(false); } } }