22 package org.matsim.core.controler;
24 import org.apache.logging.log4j.LogManager;
25 import org.apache.logging.log4j.Logger;
27 import java.util.concurrent.atomic.AtomicBoolean;
29 class MatsimRuntimeModifications {
31 private final MyRunnable runnable;
33 private volatile Throwable uncaughtException;
35 private AtomicBoolean unexpectedShutdown =
new AtomicBoolean(
false);
37 private static final Logger log = LogManager.getLogger(MatsimRuntimeModifications.class);
39 interface MyRunnable {
40 void run() throws UnexpectedShutdownException;
41 void shutdown(
boolean unexpected);
45 static class UnexpectedShutdownException extends
Exception {
48 MatsimRuntimeModifications(MyRunnable runnable) {
49 this.runnable = runnable;
52 static void run(MyRunnable runnable) {
53 new MatsimRuntimeModifications(runnable).run();
57 Thread.UncaughtExceptionHandler previousDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
58 final Thread controllerThread = Thread.currentThread();
59 Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
61 public void uncaughtException(Thread t, Throwable e) {
63 log.error(
"Getting uncaught Exception in Thread " + t.getName(), e);
64 uncaughtException = e;
65 unexpectedShutdown.set(
true);
66 controllerThread.interrupt();
71 }
catch (UnexpectedShutdownException e) {
73 }
catch (Throwable e) {
76 log.error(
"Getting uncaught Exception in Thread " + Thread.currentThread().getName(), e);
77 uncaughtException = e;
78 unexpectedShutdown.set(
true);
80 log.info(
"S H U T D O W N --- start shutdown.");
81 if (unexpectedShutdown.get()) {
82 log.error(
"ERROR --- This is an unexpected shutdown!");
84 if (uncaughtException != null) {
85 log.error(
"Shutdown possibly caused by the following Exception:", uncaughtException);
88 runnable.shutdown(unexpectedShutdown.get());
90 unexpectedShutdown.set(
true);
91 log.error(
"Exception during shutdown:", e);
92 if (uncaughtException == null) {
96 uncaughtException = e;
99 if (unexpectedShutdown.get()) {
100 log.error(
"ERROR --- MATSim unexpectedly terminated. Please check the output or the logfile with warnings and errors for hints.");
101 log.error(
"ERROR --- results should not be used for further analysis.");
103 log.info(
"S H U T D O W N --- shutdown completed.");
104 if (unexpectedShutdown.get()) {
105 log.error(
"ERROR --- This was an unexpected shutdown! See the log file for a possible reason.");
107 Thread.setDefaultUncaughtExceptionHandler(previousDefaultUncaughtExceptionHandler);
116 if (uncaughtException != null) {
118 throw ((RuntimeException) uncaughtException);
120 throw new RuntimeException(uncaughtException);