Manuel L. Santillan | 295c199 | 2006-09-09 17:48:36 +0000 | [diff] [blame] | 1 | /* |
| 2 | * This code is "ported" from JTop demo. This file defines |
| 3 | * 'jtop' function. jtop prints threads sorting by CPU time. |
| 4 | * jtop can be called once or periodically from a timer thread. |
| 5 | * To call this once, just call 'jtop()' in script console prompt. |
| 6 | * To call jtop in a timer thread, you can use |
| 7 | * |
| 8 | * var t = setTimeout(function () { jtop(print); }, 2000); |
| 9 | * |
| 10 | * The above call prints threads in sorted order for every 2 seconds. |
| 11 | * The print output goes to OS console window from which jconsole was |
| 12 | * started. The timer can be cancelled later by clearTimeout() function |
| 13 | * as shown below: |
| 14 | * |
| 15 | * clearTimeout(t); |
| 16 | */ |
| 17 | |
| 18 | /** |
| 19 | * This function returns a List of Map.Entry objects |
| 20 | * in which each entry maps cpu time to ThreadInfo. |
| 21 | */ |
| 22 | function getThreadList() { |
| 23 | var tmbean = newPlatformMXBeanProxy( |
| 24 | "java.lang:type=Threading", |
| 25 | java.lang.management.ThreadMXBean); |
| 26 | |
| 27 | if (!tmbean.isThreadCpuTimeSupported()) { |
| 28 | return; |
| 29 | } |
| 30 | |
| 31 | tmbean.setThreadCpuTimeEnabled(true); |
| 32 | |
| 33 | var tids = tmbean.allThreadIds; |
| 34 | var tinfos = tmbean["getThreadInfo(long[])"](tids); |
| 35 | |
| 36 | var map = new java.util.TreeMap(); |
| 37 | for (var i in tids) { |
| 38 | var cpuTime = tmbean.getThreadCpuTime(tids[i]); |
| 39 | if (cpuTime != -1 && tinfos[i] != null) { |
| 40 | map.put(cpuTime, tinfos[i]); |
| 41 | } |
| 42 | } |
| 43 | var list = new java.util.ArrayList(map.entrySet()); |
| 44 | java.util.Collections.reverse(list); |
| 45 | return list; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * This function prints threads sorted by CPU time. |
| 50 | * |
| 51 | * @param printFunc function called back to print [optional] |
| 52 | * |
| 53 | * By default, it uses 'echo' function to print in screen. |
| 54 | * Other choices could be 'print' (prints in console), 'alert' |
| 55 | * to show message box. Or you can define a function that writes |
| 56 | * the output to a text file. |
| 57 | */ |
| 58 | function jtop(printFunc) { |
| 59 | if (printFunc == undefined) { |
| 60 | printFunc = echo; |
| 61 | } |
| 62 | var list = getThreadList(); |
| 63 | var itr = list.iterator(); |
| 64 | printFunc("time - state - name"); |
| 65 | while (itr.hasNext()) { |
| 66 | var entry = itr.next(); |
| 67 | // time is in nanoseconds - convert to seconds |
| 68 | var time = entry.key / 1.0e9; |
| 69 | var name = entry.value.threadName; |
| 70 | var state = entry.value.threadState; |
| 71 | printFunc(time + " - " + state + " - " + name); |
| 72 | } |
| 73 | } |