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;
024import java.util.logging.Logger;
025
026/**
027 * Factories for {@link UncaughtExceptionHandler} instances.
028 *
029 * @author Gregory Kick
030 * @since 8.0
031 */
032@J2ktIncompatible
033@GwtIncompatible
034@ElementTypesAreNonnullByDefault
035public final class UncaughtExceptionHandlers {
036  private UncaughtExceptionHandlers() {}
037
038  /**
039   * Returns an exception handler that exits the system. This is particularly useful for the main
040   * thread, which may start up other, non-daemon threads, but fail to fully initialize the
041   * application successfully.
042   *
043   * <p>Example usage:
044   *
045   * <pre>
046   * public static void main(String[] args) {
047   *   Thread.currentThread().setUncaughtExceptionHandler(UncaughtExceptionHandlers.systemExit());
048   *   ...
049   * </pre>
050   *
051   * <p>The returned handler logs any exception at severity {@code SEVERE} and then shuts down the
052   * process with an exit status of 1, indicating abnormal termination.
053   */
054  public static UncaughtExceptionHandler systemExit() {
055    return new Exiter(Runtime.getRuntime());
056  }
057
058  @VisibleForTesting
059  static final class Exiter implements UncaughtExceptionHandler {
060    private static final Logger logger = Logger.getLogger(Exiter.class.getName());
061
062    private final Runtime runtime;
063
064    Exiter(Runtime runtime) {
065      this.runtime = runtime;
066    }
067
068    @Override
069    public void uncaughtException(Thread t, Throwable e) {
070      try {
071        logger.log(
072            SEVERE, String.format(Locale.ROOT, "Caught an exception in %s.  Shutting down.", t), e);
073      } catch (RuntimeException | Error errorInLogging) {
074        // If logging fails, e.g. due to missing memory, at least try to log the
075        // message and the cause for the failed logging.
076        System.err.println(e.getMessage());
077        System.err.println(errorInLogging.getMessage());
078      } finally {
079        runtime.exit(1);
080      }
081    }
082  }
083}