Skip to content

Instantly share code, notes, and snippets.

@jpospychala
Created November 6, 2012 13:27
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 jpospychala/4024731 to your computer and use it in GitHub Desktop.
Save jpospychala/4024731 to your computer and use it in GitHub Desktop.
Detects when SWT app is in Not responding state
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment