• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.util.concurrent;
18 
19 import static java.util.logging.Level.SEVERE;
20 
21 import com.google.common.annotations.VisibleForTesting;
22 
23 import java.lang.Thread.UncaughtExceptionHandler;
24 import java.util.logging.Logger;
25 
26 /**
27  * Factories for {@link UncaughtExceptionHandler} instances.
28  *
29  * @author Gregory Kick
30  * @since 8.0
31  */
32 public final class UncaughtExceptionHandlers {
UncaughtExceptionHandlers()33   private UncaughtExceptionHandlers() {}
34 
35   /**
36    * Returns an exception handler that exits the system. This is particularly useful for the main
37    * thread, which may start up other, non-daemon threads, but fail to fully initialize the
38    * application successfully.
39    *
40    * <p>Example usage:
41    * <pre>public static void main(String[] args) {
42    *   Thread.currentThread().setUncaughtExceptionHandler(UncaughtExceptionHandlers.systemExit());
43    *   ...
44    * </pre>
45    *
46    * <p>The returned handler logs any exception at severity {@code SEVERE} and then shuts down the
47    * process with an exit status of 1, indicating abnormal termination.
48    */
systemExit()49   public static UncaughtExceptionHandler systemExit() {
50     return new Exiter(Runtime.getRuntime());
51   }
52 
53   @VisibleForTesting static final class Exiter implements UncaughtExceptionHandler {
54     private static final Logger logger = Logger.getLogger(Exiter.class.getName());
55 
56     private final Runtime runtime;
57 
Exiter(Runtime runtime)58     Exiter(Runtime runtime) {
59       this.runtime = runtime;
60     }
61 
uncaughtException(Thread t, Throwable e)62     @Override public void uncaughtException(Thread t, Throwable e) {
63       try {
64         // cannot use FormattingLogger due to a dependency loop
65         logger.log(SEVERE, String.format("Caught an exception in %s.  Shutting down.", t), e);
66       } catch (Throwable errorInLogging) {
67         // If logging fails, e.g. due to missing memory, at least try to log the
68         // message and the cause for the failed logging.
69         System.err.println(e.getMessage());
70         System.err.println(errorInLogging.getMessage());
71       } finally {
72         runtime.exit(1);
73       }
74     }
75   }
76 }
77