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