@Override public void uncaughtException(Thread t, Throwable e) { if (!(e instanceof ThreadDeath)) { UncaughtExceptionHandler h = Thread.getDefaultUncaughtExceptionHandler(); if (h != null) { h.uncaughtException(t, e); return; } if (e instanceof VirtualMachineError) { // Try as hard as possible to get a stack trace from e.g. StackOverflowError e.printStackTrace(); } System.err.flush(); Exceptions.printStackTrace(e); } else { super.uncaughtException(t, e); } }
@Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(this.daemon); // If there is no specified name for thread, it will auto detect using the invoker classname instead. // Notice that auto detect may cause some performance overhead String prefix = this.name; if (StringUtils.isBlank(prefix)) { prefix = getInvoker(2); } thread.setName(prefix + "-" + getSequence(prefix)); // no specified uncaughtExceptionHandler, just do logging. if (this.uncaughtExceptionHandler != null) { thread.setUncaughtExceptionHandler(this.uncaughtExceptionHandler); } else { thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e); } }); } return thread; }
protected synchronized void startWriter () { if ( this.disposed ) { logger.warn ( "We are disposed. Not starting writer" ); return; } this.writerThread = new Thread ( "BufferingStorageDao" ) { @Override public void run () { writer (); } }; this.writerThread.start (); this.writerThread.setUncaughtExceptionHandler ( new UncaughtExceptionHandler () { @Override public void uncaughtException ( final Thread t, final Throwable e ) { logger.error ( "Writer thread failed. Restarting ...", e ); startWriter (); } } ); }
@Override public final void run() { try { _r.run(); } catch (Throwable e) { final Thread t = Thread.currentThread(); final UncaughtExceptionHandler h = t.getUncaughtExceptionHandler(); if (h != null) { h.uncaughtException(t, e); } } }
protected void resurrect(Thread t, Throwable e, @Nullable UncaughtExceptionHandler handler) { if (Looper.getMainLooper().getThread() == Thread.currentThread()) { //handle the first crash of the main looper fixRenderingAndDispatchCrash(t, e, handler); while (true) { try { Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); } catch (Throwable followUpExceptions) { //at this point, we never enter the "uncaught" exception again, because our looper is already protected print(e); fixRenderingAndDispatchCrash(t, e, handler); } } } else { //not the main thread, nothing to revive, but for the sake of consistency we treat it the same fixRenderingAndDispatchCrash(t, e, handler); } }
protected void fixRenderingAndDispatchCrash(Thread t, Throwable e, @Nullable UncaughtExceptionHandler handler) { Thread otherThread = new Thread() { @Override public void run() { mMainHandler.post(() -> { //invoke the given handler if (handler != null) { handler.uncaughtException(t, e); } //dispatch, when possible Scope appScope = ContextScope.getScope(mAppContext); if (appScope != null) { recursiveFixUI(appScope); recursiveDispatch(appScope, t, e); } }); } }; otherThread.setName("pacemaker"); otherThread.start(); }
private AppCrashHandler(Context context) { this.context = context; // get default uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); // install Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, final Throwable ex) { // save log saveException(ex, true); // uncaught uncaughtExceptionHandler.uncaughtException(thread, ex); } }); }
/** * Do some common setup for all applications at startup * @param name the application name used for Java logging and database logging */ public static void appSetup(String name) { // Set our platform wide L&F System.setProperty("swing.defaultlaf", "javax.swing.plaf.nimbus.NimbusLookAndFeel"); UIDefaults defaults = UIManager.getLookAndFeelDefaults(); defaults.put("Table.gridColor", new Color(140,140,140)); defaults.put("Table.showGrid", true); // Set the program name which is used by PostgresqlDatabase to identify the app in logs System.setProperty("program.name", name); // Start with a fresh root set at warning Logger root = LogManager.getLogManager().getLogger(""); Formatter format = new SingleLineFormatter(); root.setLevel(Level.WARNING); for(Handler handler : root.getHandlers()) { root.removeHandler(handler); } // Set prefs levels before windows preference load barfs useless data on the user Logger.getLogger("java.util.prefs").setLevel(Level.SEVERE); // postgres JDBC spits out a lot of data even though we catch the exception Logger.getLogger("org.postgresql.jdbc").setLevel(Level.OFF); Logger.getLogger("org.postgresql.Driver").setLevel(Level.OFF); // Add console handler if running in debug mode if (Prefs.isDebug()) { ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(Level.ALL); ch.setFormatter(format); root.addHandler(ch); } // For our own logs, we can set super fine level or info depending on if debug mode and attach dialogs to those Logger applog = Logger.getLogger("org.wwscc"); applog.setLevel(Prefs.isDebug() ? Level.FINEST : Level.INFO); applog.addHandler(new AlertHandler()); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { applog.log(Level.WARNING, String.format("\bUncaughtException in %s: %s", t, e), e); }}); try { File logdir = Prefs.getLogDirectory().toFile(); if (!logdir.exists()) if (!logdir.mkdirs()) throw new IOException("Can't create log directory " + logdir); FileHandler fh = new FileHandler(new File(logdir, name+".%g.log").getAbsolutePath(), 1000000, 10, true); fh.setFormatter(format); fh.setLevel(Level.ALL); root.addHandler(fh); } catch (IOException ioe) { JOptionPane.showMessageDialog(FocusManager.getCurrentManager().getActiveWindow(), "Unable to enable logging to file: " + ioe, "Log Error", JOptionPane.ERROR_MESSAGE); } // force the initialization of IdGenerator on another thread so app can start now without an odd delay later new Thread() { public void run() { IdGenerator.generateId(); } }.start(); }
/** * Creates and returns the common pool, respecting user settings specified * via system properties. */ private static ForkJoinPool makeCommonPool() { int parallelism = -1; ForkJoinWorkerThreadFactory factory = defaultForkJoinWorkerThreadFactory; UncaughtExceptionHandler handler = null; try { // ignore exceptions in accessing/parsing properties String pp = System.getProperty("java.util.concurrent.ForkJoinPool.common.parallelism"); String fp = System.getProperty("java.util.concurrent.ForkJoinPool.common.threadFactory"); String hp = System.getProperty("java.util.concurrent.ForkJoinPool.common.exceptionHandler"); if (pp != null) parallelism = Integer.parseInt(pp); if (fp != null) factory = ((ForkJoinWorkerThreadFactory) ClassLoader.getSystemClassLoader().loadClass(fp) .newInstance()); if (hp != null) handler = ((UncaughtExceptionHandler) ClassLoader.getSystemClassLoader().loadClass(hp).newInstance()); } catch (Exception ignore) { } if (parallelism < 0 && // default 1 less than #cores (parallelism = Runtime.getRuntime().availableProcessors() - 1) < 0) parallelism = 0; if (parallelism > MAX_CAP) parallelism = MAX_CAP; return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE, "ForkJoinPool.commonPool-worker-"); }
/** * Get a named {@link ThreadFactory} that just builds daemon threads. * @param prefix name prefix for all threads created from the factory * @param handler unhandles exception handler to set for all threads * @return a thread factory that creates named, daemon threads with * the supplied exception handler and normal priority */ public static ThreadFactory newDaemonThreadFactory(final String prefix, final UncaughtExceptionHandler handler) { final ThreadFactory namedFactory = getNamedThreadFactory(prefix); return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = namedFactory.newThread(r); if (handler != null) { t.setUncaughtExceptionHandler(handler); } else { t.setUncaughtExceptionHandler(LOGGING_EXCEPTION_HANDLER); } if (!t.isDaemon()) { t.setDaemon(true); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }; }
private void handleExceptionInternal(Throwable e) { UncaughtExceptionHandler exceptionHandler; exceptionHandler = getExceptionHandler(); try { if (exceptionHandler != null) { exceptionHandler.uncaughtException(Thread.currentThread(), e); } } finally { handleException(e); } }
@Override public void uncaughtException(Thread t, Throwable e) { UncaughtExceptionHandler delegate; synchronized (this) { delegate = exceptionHandler; } if (delegate != null) { delegate.uncaughtException(t, e); } }
@Test public void testExceptionHandling() throws InterruptedException { MockRunLoop runLoop = new MockRunLoop(); final Semaphore semaphore = new Semaphore(0); UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { semaphore.release(); } }; runLoop.setExceptionHandler(exceptionHandler); assertSame(exceptionHandler, runLoop.getExceptionHandler()); try { assertEquals(0, runLoop.getThreadPool().getCorePoolSize()); runLoop.scheduleNow(new Runnable() { @Override public void run() { throw new RuntimeException("test error"); } }); assertEquals(1, runLoop.getThreadPool().getCorePoolSize()); semaphore.acquire(); synchronized (runLoop.errors) { if (runLoop.errors.isEmpty()) { runLoop.errors.wait(TestUtils.TEST_TIMEOUT_MILLIS); } } assertEquals(1, runLoop.errors.size()); } finally { runLoop.getExecutorService().shutdownNow(); } }
@Override public Thread newThread(Runnable r) { if (r == null) { return null; } Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setUncaughtExceptionHandler( new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { // ignore -- to prevent the test output from getting cluttered } }); return thread; }
/** * Have shutdown actually means shutdown. Tasks that need to complete should use * futures. */ public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, UncaughtExceptionHandler handler, int poolSize, int stackSize) { // HACK: ScheduledThreadPoolExecutor won't let use the handler so // if we're using ExceptionHandlingRunnable then we'll be able to // pick up the exceptions Thread.setDefaultUncaughtExceptionHandler(handler); ThreadFactory factory = getThreadFactory(name, handler); ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(poolSize, factory); executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); return executor; }
public static ThreadFactory getThreadFactory(final String name, final UncaughtExceptionHandler handler) { return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(null, r, name, 1024*1024); t.setDaemon(true); t.setUncaughtExceptionHandler(handler); return t; } }; }
public RedissonThreadFactory(UncaughtExceptionHandler exceptionHandler) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "redisson-node-" + poolNumber.getAndIncrement() + "-thread-"; this.exceptionHandler = exceptionHandler; }
public BrambleTestCase() { // Ensure exceptions thrown on worker threads cause tests to fail UncaughtExceptionHandler fail = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { throwable.printStackTrace(); fail(); } }; Thread.setDefaultUncaughtExceptionHandler(fail); }
@Override public void startLoggingThread(LogWriter writer, UncaughtExceptionHandler exceptionHandler) { Thread writerThread = new Thread(writer); writerThread.setName("log4j-aws-writer-" + threadNumber.getAndIncrement()); writerThread.setPriority(Thread.NORM_PRIORITY); writerThread.setUncaughtExceptionHandler(exceptionHandler); writerThread.start(); }
private void invokeOnExecutionThreadForTest(Runnable runnable) { executionThread = new Thread(runnable); executionThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable e) { thrownByExecutionThread = e; } }); executionThread.start(); }
@Override public void execute(Runnable command) { executionThread = new Thread(command); executionThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable e) { thrownByExecutionThread = e; } }); executionThread.start(); }
@Test public void onErrorNoHandler() { try { final List<Throwable> list = new ArrayList<Throwable>(); RxJavaCommonPlugins.setErrorHandler(null); Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { list.add(e); } }); RxJavaCommonPlugins.onError(new TestException("Forced failure")); Thread.currentThread().setUncaughtExceptionHandler(null); // this will be printed on the console and should not crash RxJavaCommonPlugins.onError(new TestException("Forced failure 3")); assertEquals(1, list.size()); assertUndeliverableTestException(list, 0, "Forced failure"); } finally { RxJavaCommonPlugins.reset(); Thread.currentThread().setUncaughtExceptionHandler(null); } }
@Test public void pluginCrash() { Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { throw new TestException("Second"); } }); CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(new Runnable() { @Override public void run() { throw new TestException("First"); } }, set); set.add(run); try { run.run(); fail("Should have thrown!"); } catch (TestException ex) { assertEquals("Second", ex.getMessage()); } finally { Thread.currentThread().setUncaughtExceptionHandler(null); } assertTrue(run.isDisposed()); assertEquals(0, set.size()); }
@Test public void testDefaultUncaughtExceptionHandler() throws InterruptedException { final AtomicBoolean defaultHandlerCalled = new AtomicBoolean(false); final UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler(); try { Thread.setDefaultUncaughtExceptionHandler( (thread, throwable) -> defaultHandlerCalled.set(true)); final FailingLooperThread failingThread = new FailingLooperThread(); failingThread.start(); failingThread.join(); Thread.sleep(1000); assertTrue(defaultHandlerCalled.get()); } finally { Thread.setDefaultUncaughtExceptionHandler(oldHandler); } }
private Set<UncaughtExceptionHandler> c() { Set<UncaughtExceptionHandler> keySet; synchronized (this.c) { keySet = this.c.keySet(); } return keySet; }
private void a(Thread thread, Throwable th) { for (UncaughtExceptionHandler uncaughtException : c()) { try { uncaughtException.uncaughtException(thread, th); } catch (Throwable th2) { } } }
private void initialise() { Thread managers = new Thread(() -> { List<Lexicon> lexicons = RemoteService.lexiconServiceRemote.findAll(); LexiconManager.getInstance().loadLexicons(lexicons); // LexiconManager.getInstance().loadLexicons(RemoteService.lexiconServiceRemote.findAll()); PartOfSpeechManager.getInstance(); DomainManager.getInstance(); List<RelationType> relations = RemoteService.relationTypeRemote.findAll(); RelationTypeManager.getInstance().loadRelationTypes(relations); // RelationTypeManager.getInstance().loadRelationTypes(RemoteService.relationTypeRemote.findAll()); start(); }, "Mangers Thread"); managers.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { private boolean first = true; @Override public void uncaughtException(Thread t, Throwable tt) { if (first) { SwingUtilities.invokeLater(() -> { JOptionPane.showMessageDialog(null, Messages.ERROR_UNABLE_TO_CONNECT_TO_SERVER, Application.PROGRAM_NAME_VERSION, JOptionPane.ERROR_MESSAGE); }); first = false; } try { Thread.sleep(13000); } catch (InterruptedException e) { } System.exit(1); } }); managers.start(); }
/** * Install your delegated exception handler. You will be called by all threads, which have been crashed. * If this was the main looper, you will be posted. So usually you want to inspect your scopes and * send the user to some info UIS. See also {@link UnbreakableCrashHandler} * * @param handler the crashing callback, always invoked from the main thread (posted at any time in the future after the crash) */ public void install(Context context, @Nullable UncaughtExceptionHandler handler) { mAppContext = context; Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { print(e); resurrect(t, e, handler); } }); }
protected void recursiveDispatch(Scope root, Thread t, Throwable e) { root.forEachEntry(entry -> { if (entry.getValue() instanceof UncaughtExceptionHandler) { ((UncaughtExceptionHandler) entry.getValue()).uncaughtException(t, e); } return true; }); root.forEachScope(scope -> { recursiveDispatch(scope, t, e); return true; }); }
/** * Callback from ForkJoinWorkerThread constructor to establish and * record its WorkQueue. * * @param wt the worker thread * @return the worker's queue */ final WorkQueue registerWorker(ForkJoinWorkerThread wt) { UncaughtExceptionHandler handler; wt.setDaemon(true); // configure thread if ((handler = ueh) != null) wt.setUncaughtExceptionHandler(handler); WorkQueue w = new WorkQueue(this, wt); int i = 0; // assign a pool index int mode = config & MODE_MASK; int rs = lockRunState(); try { WorkQueue[] ws; int n; // skip if no array if ((ws = workQueues) != null && (n = ws.length) > 0) { int s = indexSeed += SEED_INCREMENT; // unlikely to collide int m = n - 1; i = ((s << 1) | 1) & m; // odd-numbered indices if (ws[i] != null) { // collision int probes = 0; // step by approx half n int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2; while (ws[i = (i + step) & m] != null) { if (++probes >= n) { workQueues = ws = Arrays.copyOf(ws, n <<= 1); m = n - 1; probes = 0; } } } w.hint = s; // use as random seed w.config = i | mode; w.scanState = i; // publication fence ws[i] = w; } } finally { unlockRunState(rs, rs & ~RSLOCK); } wt.setName(workerNamePrefix.concat(Integer.toString(i >>> 1))); return w; }
/** * Creates a {@code ForkJoinPool} with the given parameters, without * any security checks or parameter validation. Invoked directly by * makeCommonPool. */ private ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory, UncaughtExceptionHandler handler, int mode, String workerNamePrefix) { this.workerNamePrefix = workerNamePrefix; this.factory = factory; this.ueh = handler; this.config = (parallelism & SMASK) | mode; long np = (long)(-parallelism); // offset ctl counts this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); }
/** * Creates and returns the common pool, respecting user settings * specified via system properties. */ private static ForkJoinPool makeCommonPool() { int parallelism = -1; ForkJoinWorkerThreadFactory factory = null; UncaughtExceptionHandler handler = null; try { // ignore exceptions in accessing/parsing properties String pp = System.getProperty ("java.util.concurrent.ForkJoinPool.common.parallelism"); String fp = System.getProperty ("java.util.concurrent.ForkJoinPool.common.threadFactory"); String hp = System.getProperty ("java.util.concurrent.ForkJoinPool.common.exceptionHandler"); if (pp != null) parallelism = Integer.parseInt(pp); if (fp != null) factory = ((ForkJoinWorkerThreadFactory)ClassLoader. getSystemClassLoader().loadClass(fp).newInstance()); if (hp != null) handler = ((UncaughtExceptionHandler)ClassLoader. getSystemClassLoader().loadClass(hp).newInstance()); } catch (Exception ignore) { } if (factory == null) { if (System.getSecurityManager() == null) factory = defaultForkJoinWorkerThreadFactory; else // use security-managed default factory = new InnocuousForkJoinWorkerThreadFactory(); } if (parallelism < 0 && // default 1 less than #cores (parallelism = Runtime.getRuntime().availableProcessors() - 1) <= 0) parallelism = 1; if (parallelism > MAX_CAP) parallelism = MAX_CAP; return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE, "ForkJoinPool.commonPool-worker-"); }
static void enable(@Nonnull Bugsnag bugsnag) { UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler(); // Find or create the Bugsnag ExceptionHandler LoggedUncaughtExceptionHandler bugsnagHandler; if (currentHandler instanceof LoggedUncaughtExceptionHandler) { bugsnagHandler = (LoggedUncaughtExceptionHandler) currentHandler; } else { bugsnagHandler = new LoggedUncaughtExceptionHandler(currentHandler); Thread.setDefaultUncaughtExceptionHandler(bugsnagHandler); } // Subscribe this bugsnag to uncaught exceptions bugsnagHandler.clientMap.put(bugsnag, true); }
static void disable(@Nonnull Bugsnag bugsnag) { // Find the Bugsnag ExceptionHandler UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler(); if (currentHandler instanceof LoggedUncaughtExceptionHandler) { // Unsubscribe this bugsnag from uncaught exceptions LoggedUncaughtExceptionHandler bugsnagHandler = (LoggedUncaughtExceptionHandler) currentHandler; bugsnagHandler.clientMap.remove(bugsnag); // Remove the Bugsnag ExceptionHandler if no clients are subscribed if (bugsnagHandler.clientMap.size() == 0) { Thread.setDefaultUncaughtExceptionHandler(bugsnagHandler.originalHandler); } } }
public WebSocketWorker() { setName("WebSocketWorker-" + getId()); setUncaughtExceptionHandler(new UncaughtExceptionHandler(WebSocketServer.this) { public void uncaughtException(Thread t, Throwable e) { Thread.getDefaultUncaughtExceptionHandler().uncaughtException(t, e); } }); }