Merge branch '1.3.x'

This commit is contained in:
Andy Wilkinson
2016-06-17 09:58:45 +01:00
2 changed files with 115 additions and 1 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,11 +17,13 @@
package org.springframework.boot.devtools.restart;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Arrays;
/**
* {@link UncaughtExceptionHandler} decorator that allows a thread to exit silently.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
class SilentExitExceptionHandler implements UncaughtExceptionHandler {
@@ -34,6 +36,9 @@ class SilentExitExceptionHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread thread, Throwable exception) {
if (exception instanceof SilentExitException) {
if (jvmWillExit(thread)) {
preventNonZeroExitCode();
}
return;
}
if (this.delegate != null) {
@@ -53,6 +58,41 @@ 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 {
}