Created
November 6, 2012 13:27
-
-
Save jpospychala/4024731 to your computer and use it in GitHub Desktop.
Detects when SWT app is in Not responding state
This file contains hidden or 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
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