1818import  com .google .common .annotations .VisibleForTesting ;
1919import  com .google .common .base .Throwables ;
2020import  com .hivemq .exceptions .UnrecoverableException ;
21+ import  com .hivemq .extension .sdk .api .annotations .NotNull ;
2122import  org .slf4j .Logger ;
2223import  org .slf4j .LoggerFactory ;
2324
25+ import  java .util .concurrent .Callable ;
26+ import  java .util .concurrent .atomic .AtomicReference ;
27+ 
2428/** 
2529 * @author Dominik Obermaier 
2630 */ 
2731public  class  HiveMQExceptionHandlerBootstrap  {
2832
2933    private  static  final  Logger  log  = LoggerFactory .getLogger (HiveMQExceptionHandlerBootstrap .class );
3034
35+     private  static  final  AtomicReference <Runnable > terminator  = new  AtomicReference <>(() -> System .exit (1 ));
36+ 
3137    /** 
3238     * Adds an uncaught Exception Handler for UnrecoverableExceptions. 
3339     * Logs the error and quits HiveMQ 
3440     */ 
3541    public  static  void  addUnrecoverableExceptionHandler () {
36-         Thread .setDefaultUncaughtExceptionHandler (new  Thread .UncaughtExceptionHandler () {
37-             @ Override 
38-             public  void  uncaughtException (final  Thread  t , final  Throwable  e ) {
42+         Thread .setDefaultUncaughtExceptionHandler (HiveMQExceptionHandlerBootstrap ::handleUncaughtException );
43+     }
3944
40-                 handleUncaughtException (t , e );
41-             }
42-         });
45+     public  static  void  setTerminator (@ NotNull  final  Runnable  runnable ) {
46+         terminator .set (runnable );
4347    }
4448
4549    @ VisibleForTesting 
@@ -48,16 +52,14 @@ static void handleUncaughtException(final Thread t, final Throwable e) {
4852            if  (((UnrecoverableException ) e ).isShowException ()) {
4953                log .error ("An unrecoverable Exception occurred. Exiting HiveMQ" , t , e );
5054            }
51-             System . exit ( 1 );
55+             terminator . get (). run ( );
5256        }
5357        final  Throwable  rootCause  = Throwables .getRootCause (e );
5458        if  (rootCause  instanceof  UnrecoverableException ) {
5559            final  boolean  showException  = ((UnrecoverableException ) rootCause ).isShowException ();
5660            if  (showException ) {
5761                log .error ("Cause: " , e );
5862            }
59-         } else  if  (rootCause  instanceof  ThreadDeath ) {
60-            // NOOP: this happens when tests stop the remaining threads via thread.stop(); 
6163        } else  {
6264            log .error ("Uncaught Error:" , e );
6365        }
0 commit comments