Skip to content

Instantly share code, notes, and snippets.

@danielshaya
Created February 11, 2015 13:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielshaya/b940f5e3522ea174dd40 to your computer and use it in GitHub Desktop.
Save danielshaya/b940f5e3522ea174dd40 to your computer and use it in GitHub Desktop.
Class to demonstrate the use of Monitor
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;
}
}
}
}
}
@nithinnambiar
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment