Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

nithinnambiar commented Feb 17, 2015

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
You can’t perform that action at this time.