
javadoc.src-html.com.google.common.util.concurrent.UncaughtExceptionHandlers.html Maven / Gradle / Ivy
The newest version!
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
017 package com.google.common.util.concurrent;
018
019 import static java.util.logging.Level.SEVERE;
020
021 import com.google.common.annotations.VisibleForTesting;
022
023 import java.lang.Thread.UncaughtExceptionHandler;
024 import java.util.logging.Logger;
025
026 /**
027 * Factories for {@link UncaughtExceptionHandler} instances.
028 *
029 * @author Gregory Kick
030 * @since 8.0
031 */
032 public 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 public static UncaughtExceptionHandler systemExit() {
047 return new Exiter(Runtime.getRuntime());
048 }
049
050 @VisibleForTesting static final class Exiter implements UncaughtExceptionHandler {
051 private static final Logger logger = Logger.getLogger(Exiter.class.getName());
052
053 private final Runtime runtime;
054
055 Exiter(Runtime runtime) {
056 this.runtime = runtime;
057 }
058
059 @Override public void uncaughtException(Thread t, Throwable e) {
060 // cannot use FormattingLogger due to a dependency loop
061 logger.log(SEVERE, String.format("Caught an exception in %s. Shutting down.", t), e);
062 runtime.exit(1);
063 }
064 }
065 }
© 2015 - 2025 Weber Informatics LLC | Privacy Policy