Created
February 11, 2015 13:46
-
-
Save danielshaya/b940f5e3522ea174dd40 to your computer and use it in GitHub Desktop.
Class to demonstrate the use of Monitor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example; | |
import java.util.concurrent.atomic.AtomicLong; | |
import java.util.logging.Logger; | |
import java.util.stream.Stream; | |
/** | |
* Class to demonstrate the use of Monitor | |
*/ | |
public class FindSlowCode { | |
public static void main(String[] args) { | |
new FindSlowCode().run(); | |
} | |
private void run() { | |
Monitor monitor = new Monitor(Thread.currentThread(), 8); | |
Thread thread = new Thread(monitor, "MonitorThread"); | |
thread.setDaemon(true); | |
thread.start(); | |
while(true) { | |
monitor.reset(); | |
double x=0; | |
for (int i = 0; i < 10_000; i++) { | |
x += Math.sqrt(i); | |
Logger.getLogger(getClass().getName()).fine("x=" + x); | |
} | |
} | |
} | |
public static class Monitor implements Runnable{ | |
private final Thread thread; | |
private final AtomicLong startTime = new AtomicLong(Long.MAX_VALUE); | |
private final int thresholdMS; | |
public Monitor(Thread thread, int thresholdMS){ | |
this.thread = thread; | |
this.thresholdMS = thresholdMS; | |
} | |
public void reset(){ | |
startTime.set(System.currentTimeMillis()); | |
} | |
@Override | |
public void run(){ | |
while(thread.isAlive()){ | |
long timeTaken = System.currentTimeMillis()-startTime.get(); | |
if(timeTaken > thresholdMS){ | |
System.out.println(timeTaken + "----------------------------"); | |
Stream.of(thread.getStackTrace()).forEach(System.out::println); | |
} | |
try { | |
Thread.sleep(thresholdMS/2); | |
} catch (InterruptedException e) { | |
break; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing. Looks very interesting, but in a multi threaded application it might be difficult to manage monitors as you might not have control of the thread which executes your critical sections of your code.