Merge branch '1.3.x'

This commit is contained in:
Phillip Webb
2016-06-20 18:50:00 -07:00
7 changed files with 51 additions and 48 deletions

View File

@@ -36,7 +36,7 @@ class SilentExitExceptionHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread thread, Throwable exception) {
if (exception instanceof SilentExitException) {
if (jvmWillExit(thread)) {
if (isJvmExiting(thread)) {
preventNonZeroExitCode();
}
return;
@@ -46,6 +46,38 @@ class SilentExitExceptionHandler implements UncaughtExceptionHandler {
}
}
private boolean isJvmExiting(Thread exceptionThread) {
for (Thread thread : getAllThreads()) {
if (thread != exceptionThread && thread.isAlive() && !thread.isDaemon()) {
return false;
}
}
return true;
}
protected Thread[] getAllThreads() {
ThreadGroup rootThreadGroup = getRootThreadGroup();
Thread[] threads = new Thread[32];
int count = rootThreadGroup.enumerate(threads);
while (count == threads.length) {
threads = new Thread[threads.length * 2];
count = rootThreadGroup.enumerate(threads);
}
return Arrays.copyOf(threads, count);
}
private ThreadGroup getRootThreadGroup() {
ThreadGroup candidate = Thread.currentThread().getThreadGroup();
while (candidate.getParent() != null) {
candidate = candidate.getParent();
}
return candidate;
}
protected void preventNonZeroExitCode() {
System.exit(0);
}
public static void setup(Thread thread) {
UncaughtExceptionHandler handler = thread.getUncaughtExceptionHandler();
if (!(handler instanceof SilentExitExceptionHandler)) {
@@ -58,41 +90,6 @@ class SilentExitExceptionHandler implements UncaughtExceptionHandler {
throw new SilentExitException();
}
private boolean jvmWillExit(Thread exceptionThread) {
for (Thread thread : getAllThreads()) {
if (thread != exceptionThread && thread.isAlive() && !thread.isDaemon()) {
return false;
}
}
return true;
}
protected void preventNonZeroExitCode() {
System.exit(0);
}
protected Thread[] getAllThreads() {
ThreadGroup rootThreadGroup = getRootThreadGroup();
int size = 32;
int threadCount;
Thread[] threads;
do {
size *= 2;
threads = new Thread[size];
threadCount = rootThreadGroup.enumerate(threads);
}
while (threadCount == threads.length);
return Arrays.copyOf(threads, threadCount);
}
private ThreadGroup getRootThreadGroup() {
ThreadGroup candidate = Thread.currentThread().getThreadGroup();
while (candidate.getParent() != null) {
candidate = candidate.getParent();
}
return candidate;
}
private static class SilentExitException extends RuntimeException {
}

View File

@@ -27,6 +27,7 @@ import static org.junit.Assert.fail;
* Tests for {@link SilentExitExceptionHandler}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class SilentExitExceptionHandlerTests {