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.logging.Logger;
025
026/**
027 * Factories for {@link UncaughtExceptionHandler} instances.
028 *
029 * @author Gregory Kick
030 * @since 8.0
031 */
032public final class UncaughtExceptionHandlers {
033  private UncaughtExceptionHandlers() {}
034
035  /**
036   * Returns an exception handler that exits the system. This is particularly useful for the main
037   * thread, which may start up other, non-daemon threads, but fail to fully initialize the
038   * application successfully.
039   *
040   * <p>Example usage:
041   * <pre>public static void main(String[] args) {
042   *   Thread.currentThread().setUncaughtExceptionHandler(UncaughtExceptionHandlers.systemExit());
043   *   ...
044   * </pre>
045   *
046   * <p>The returned handler logs any exception at severity {@code SEVERE} and then shuts down the
047   * process with an exit status of 1, indicating abnormal termination.
048   */
049  public static UncaughtExceptionHandler systemExit() {
050    return new Exiter(Runtime.getRuntime());
051  }
052
053  @VisibleForTesting static final class Exiter implements UncaughtExceptionHandler {
054    private static final Logger logger = Logger.getLogger(Exiter.class.getName());
055
056    private final Runtime runtime;
057
058    Exiter(Runtime runtime) {
059      this.runtime = runtime;
060    }
061
062    @Override public void uncaughtException(Thread t, Throwable e) {
063      // cannot use FormattingLogger due to a dependency loop
064      logger.log(SEVERE, String.format("Caught an exception in %s.  Shutting down.", t), e);
065      runtime.exit(1);
066    }
067  }
068}