Skip to content

Instantly share code, notes, and snippets.

@jpospychala
Created November 6, 2012 13:27
Show Gist options
  • Save jpospychala/4024731 to your computer and use it in GitHub Desktop.
Save jpospychala/4024731 to your computer and use it in GitHub Desktop.

Revisions

  1. jpospychala created this gist Nov 6, 2012.
    70 changes: 70 additions & 0 deletions DetectNoResponse.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    import java.util.Iterator;
    import java.util.Map;

    import org.eclipse.swt.widgets.Display;

    public class DetectNoResponse {

    // timeout (msec) minimal time of no response to detect
    protected long timeout = 1000;
    protected long displayThreadResponse;
    private boolean isRunning;

    public void start() {
    isRunning = true;
    Thread t = new Thread(new Runnable() {
    public void run() {
    displayThreadResponse = System.currentTimeMillis();
    while ((!Display.getDefault().isDisposed()) && isRunning) {
    pingDisplayThread();
    long now = System.currentTimeMillis();

    try {
    Thread.sleep(timeout);
    } catch (InterruptedException e) {
    // ignore
    }

    long responseTime = Math.abs(now - displayThreadResponse);
    if (responseTime > timeout) {
    System.err.println("No response for "+responseTime);
    System.err.println(captureThreadDump());
    }
    }
    }
    });
    t.start();
    }

    public static String captureThreadDump() {
    // from http://henryranch.net/software/capturing-a-thread-dump-in-java/
    Map allThreads = Thread.getAllStackTraces();
    Iterator iterator = allThreads.keySet().iterator();
    StringBuffer stringBuffer = new StringBuffer();
    while (iterator.hasNext()) {
    Thread key = (Thread) iterator.next();
    StackTraceElement[] trace = (StackTraceElement[]) allThreads
    .get(key);
    stringBuffer.append(key + "\r\n");
    for (int i = 0; i < trace.length; i++) {
    stringBuffer.append(" " + trace[i] + "\r\n");
    }
    stringBuffer.append("");
    }
    return stringBuffer.toString();
    }

    protected void pingDisplayThread() {
    Display.getDefault().asyncExec(new Runnable() {

    public void run() {
    displayThreadResponse = System.currentTimeMillis();
    }
    });
    }

    public void stop() {
    isRunning = false;
    }

    }