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
17package com.google.common.util.concurrent;
18
19import static java.util.logging.Level.SEVERE;
20
21import com.google.common.annotations.VisibleForTesting;
22
23import java.lang.Thread.UncaughtExceptionHandler;
24import java.util.logging.Logger;
25
26/**
27 * Factories for {@link UncaughtExceptionHandler} instances.
28 *
29 * @author Gregory Kick
30 * @since 8.0
31 */
32public final class 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  public static UncaughtExceptionHandler systemExit() {
47    return new Exiter(Runtime.getRuntime());
48  }
49
50  @VisibleForTesting static final class Exiter implements UncaughtExceptionHandler {
51    private static final Logger logger = Logger.getLogger(Exiter.class.getName());
52
53    private final Runtime runtime;
54
55    Exiter(Runtime runtime) {
56      this.runtime = runtime;
57    }
58
59    @Override public void uncaughtException(Thread t, Throwable e) {
60      // cannot use FormattingLogger due to a dependency loop
61      logger.log(SEVERE, String.format("Caught an exception in %s.  Shutting down.", t), e);
62      runtime.exit(1);
63    }
64  }
65}
66