Not particularly efficient or perfectly accurate but is great at fast thread switching detection @author dan
| 27 | * @author dan |
| 28 | */ |
| 29 | public class ThreadMonitor extends Thread { |
| 30 | private final Thread monitor; |
| 31 | private final ChronoLatch cl; |
| 32 | private final RollingSequence sq = new RollingSequence(3); |
| 33 | int cycles = 0; |
| 34 | private boolean running; |
| 35 | private State lastState; |
| 36 | private PrecisionStopwatch st; |
| 37 | |
| 38 | private ThreadMonitor(Thread monitor) { |
| 39 | running = true; |
| 40 | st = PrecisionStopwatch.start(); |
| 41 | this.monitor = monitor; |
| 42 | lastState = State.NEW; |
| 43 | cl = new ChronoLatch(1000); |
| 44 | start(); |
| 45 | } |
| 46 | |
| 47 | public static ThreadMonitor bind(Thread monitor) { |
| 48 | return new ThreadMonitor(monitor); |
| 49 | } |
| 50 | |
| 51 | public void run() { |
| 52 | while (running) { |
| 53 | try { |
| 54 | Thread.sleep(0); |
| 55 | State s = monitor.getState(); |
| 56 | if (lastState != s) { |
| 57 | cycles++; |
| 58 | pushState(s); |
| 59 | } |
| 60 | |
| 61 | lastState = s; |
| 62 | |
| 63 | if (cl.flip()) { |
| 64 | Adapt.info("Cycles: " + Form.f(cycles) + " (" + Form.duration(sq.getAverage(), 2) + ")"); |
| 65 | } |
| 66 | } catch (Throwable e) { |
| 67 | running = false; |
| 68 | break; |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | public void pushState(State s) { |
| 74 | if (s != State.RUNNABLE) { |
| 75 | if (st != null) { |
| 76 | sq.put(st.getMilliseconds()); |
| 77 | } |
| 78 | } else { |
| 79 | |
| 80 | st = PrecisionStopwatch.start(); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | public void unbind() { |
| 85 | running = false; |
| 86 | } |
nothing calls this directly
no outgoing calls
no test coverage detected