001/*
002 * Copyright (C) 2010 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static java.util.logging.Level.SEVERE;
018
019import com.google.common.annotations.GwtIncompatible;
020import com.google.common.annotations.J2ktIncompatible;
021import com.google.common.annotations.VisibleForTesting;
022import java.lang.Thread.UncaughtExceptionHandler;
023import java.util.Locale;
024
025/**
026 * Factories for {@link UncaughtExceptionHandler} instances.
027 *
028 * @author Gregory Kick
029 * @since 8.0
030 */
031@J2ktIncompatible
032@GwtIncompatible
033@ElementTypesAreNonnullByDefault
034public final class UncaughtExceptionHandlers {
035  private UncaughtExceptionHandlers() {}
036
037  /**
038   * Returns an exception handler that exits the system. This is particularly useful for the main
039   * thread, which may start up other, non-daemon threads, but fail to fully initialize the
040   * application successfully.
041   *
042   * <p>Example usage:
043   *
044   * <pre>
045   * public static void main(String[] args) {
046   *   Thread.currentThread().setUncaughtExceptionHandler(UncaughtExceptionHandlers.systemExit());
047   *   ...
048   * </pre>
049   *
050   * <p>The returned handler logs any exception at severity {@code SEVERE} and then shuts down the
051   * process with an exit status of 1, indicating abnormal termination.
052   */
053  public static UncaughtExceptionHandler systemExit() {
054    return new Exiter(Runtime.getRuntime());
055  }
056
057  @VisibleForTesting
058  static final class Exiter implements UncaughtExceptionHandler {
059    private static final LazyLogger logger = new LazyLogger(Exiter.class);
060
061    private final Runtime runtime;
062
063    Exiter(Runtime runtime) {
064      this.runtime = runtime;
065    }
066
067    @Override
068    public void uncaughtException(Thread t, Throwable e) {
069      try {
070        logger
071            .get()
072            .log(
073                SEVERE,
074                String.format(Locale.ROOT, "Caught an exception in %s.  Shutting down.", t),
075                e);
076      } catch (Throwable errorInLogging) { // sneaky checked exception
077        // If logging fails, e.g. due to missing memory, at least try to log the
078        // message and the cause for the failed logging.
079        System.err.println(e.getMessage());
080        System.err.println(errorInLogging.getMessage());
081      } finally {
082        runtime.exit(1);
083      }
084    }
085  }
086}