java.lang.Thread.UncaughtExceptionHandler Java Examples

The following examples show how to use java.lang.Thread.UncaughtExceptionHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RevertDefaultThreadHandlerRule.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(Statement s, Description d) {
  return new StatementAdapter(s) {
    @Override
    protected void before() throws Throwable {
      if (!applied.getAndSet(true)) {
        UncaughtExceptionHandler p = Thread.getDefaultUncaughtExceptionHandler();
        try {
          // Try to initialize a zookeeper class that reinitializes default exception handler.
          Class<?> cl = NIOServerCnxnFactory.class;
          // Make sure static initializers have been called.
          Class.forName(cl.getName(), true, cl.getClassLoader());
        } finally {
          if (p == Thread.getDefaultUncaughtExceptionHandler()) {
          //  throw new RuntimeException("Zookeeper no longer resets default thread handler.");
          }
          Thread.setDefaultUncaughtExceptionHandler(p);
        }
      }
    }
  };
}
 
Example #2
Source File: BufferingStorageDao.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
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 ();
        }
    } );
}
 
Example #3
Source File: ThreadedJaasAuthenticateTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public void testThreads() throws InterruptedException {
	UncaughtExceptionHandler handler = Thread.currentThread().getUncaughtExceptionHandler();
	Thread[] threads = new Thread[threadCount];
	Random rnd = new Random();
	for (int i = 0; i < threadCount ; i++) {
		String name;
		if (rnd.nextBoolean()) {
			name = "Thread-"+ i+ "-good";
			threads[i] = new Thread(new Authenticate(goodUser, goodPass, true), name);
		} else {
			name = "Thread-"+ i+ "-bad";
			threads[i] = new Thread(new Authenticate(badUser, badPass, false), name);
		}
		threads[i].setUncaughtExceptionHandler(handler);
		threads[i].start();
		log.info("Started "+ name);
	}
	for (Thread thread: threads) {
		thread.join();
	}
}
 
Example #4
Source File: StandaloneStatMonitor.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("static-access")
@Override
public void run() {
	Thread.currentThread().setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
		@Override
		public void uncaughtException(Thread arg0, Throwable arg1) {
			logger.error("[error]{}:{}",slaveRedis.getIp(), slaveRedis.getPort(), arg1);
			Cat.logError(arg1);
			redisStatCheckResult.put(slaveRedis, Boolean.FALSE);
			if (null != slave) {
				slave.close();
			}
		}
	});

	logger.debug("[Psubscribe]{}:{}", slaveRedis.getIp(), slaveRedis.getPort());
	slave.psubscribe(new JedisPubSub() {
		@Override
		public void onPMessage(String pattern, String channel, String msg) {
			logger.debug("[OnPMessage]{}:{}", slaveRedis.getIp(), slaveRedis.getPort());
			redisStatCheckResult.put(slaveRedis, Boolean.TRUE);
		}
	}, generateURL(masterRedis.getIp(), masterRedis.getPort()));
}
 
Example #5
Source File: VectorImage.java    From pumpernickel with MIT License 6 votes vote down vote up
private void writeObject(java.io.ObjectOutputStream out)
		throws IOException {
	out.writeInt(0);
	out.writeObject(operations.toArray(new Operation[operations.size()]));
	out.writeInt(operations.getTimeoutSeconds());

	ArrayListener<Operation>[] arrayListeners = operations
			.getArrayListeners();
	ChangeListener[] changeListeners = operations.getChangeListeners();
	ListListener<Operation>[] listListeners = operations.getListListeners();

	nullifyUnserializable(arrayListeners);
	nullifyUnserializable(changeListeners);
	nullifyUnserializable(listListeners);

	out.writeObject(arrayListeners);
	out.writeObject(changeListeners);
	out.writeObject(listListeners);

	UncaughtExceptionHandler ueh = operations
			.getListenerUncaughtExceptionHandler();
	if (!(ueh instanceof Serializable))
		ueh = null;

	out.writeObject(ueh);
}
 
Example #6
Source File: Application.java    From Augendiagnose with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Define custom ExceptionHandler which takes action on OutOfMemoryError.
 */
private void setExceptionHandler() {
	final UncaughtExceptionHandler defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();

	UncaughtExceptionHandler customExceptionHandler =
			new UncaughtExceptionHandler() {
				@Override
				public void uncaughtException(final Thread thread, final Throwable ex) {
					if (ex instanceof OutOfMemoryError) {
						// Store info about OutOfMemoryError
						PreferenceUtil.setSharedPreferenceBoolean(R.string.key_internal_outofmemoryerror, true);
					}

					// re-throw critical exception further to the os
					defaultExceptionHandler.uncaughtException(thread, ex);
				}
			};

	Thread.setDefaultUncaughtExceptionHandler(customExceptionHandler);
}
 
Example #7
Source File: ThreadFactoryGenerator.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
public static final ThreadFactory generateFactory(boolean daemon, String threadGroupName) {
    String namePattern = "%G-%t";
    UncaughtExceptionHandler uncaughtExceptionHandler = null;
    Integer initialPriority = null;
    Long stackSize = null;
    return new JBossThreadFactory(
            new ThreadGroup(threadGroupName),
            daemon,
            initialPriority,
            namePattern,
            uncaughtExceptionHandler,
            stackSize,
            null); // this last param is ignored according to docs.
    // see: https://github.com/jbossas/jboss-threads/blob/2.2/src/main/java/org/jboss/threads/JBossThreadFactory.java#L90
}
 
Example #8
Source File: ForkJoinPool.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: ForkJoinPool.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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-");
}
 
Example #10
Source File: HookThrowing.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    RxJavaPlugins.setErrorHandler(ex -> {
        UncaughtExceptionHandler h = Thread.currentThread().getUncaughtExceptionHandler();
        Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
            Thread.currentThread().setUncaughtExceptionHandler(h);
            HookThrowing.sneakyThrow(ex);
        });
        throw new RuntimeException("Fail up");
    });
}
 
Example #11
Source File: ThreadFactoryBuilder.java    From HubBasics with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ThreadFactoryBuilder setUncaughtExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler) {
    if (null == uncaughtExceptionHandler) {
        throw new NullPointerException("UncaughtExceptionHandler cannot be null");
    }
    this.uncaughtExceptionHandler = uncaughtExceptionHandler;
    return this;
}
 
Example #12
Source File: NamingThreadFactory.java    From ecp-uid with Apache License 2.0 5 votes vote down vote up
@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.isEmpty(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() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e);
            }
        });
    }

    return thread;
}
 
Example #13
Source File: TransactionalRegionServer.java    From hbase-secondary-index with GNU General Public License v3.0 5 votes vote down vote up
public static HasThread setDaemonThreadRunning(final HasThread t,
		final String name, final UncaughtExceptionHandler handler) {
	t.setName(name);
	if (handler != null) {
		t.setUncaughtExceptionHandler(handler);
	}
	t.setDaemon(true);

	t.start();
	return t;
}
 
Example #14
Source File: ThreadTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.lang.Thread#getDefaultUncaughtExceptionHandler
 * java.lang.Thread#setDefaultUncaughtExceptionHandler
 */
public void test_get_setDefaultUncaughtExceptionHandler() {
    class Handler implements UncaughtExceptionHandler {
        public void uncaughtException(Thread thread, Throwable ex) {
        }
    }

    final Handler handler = new Handler();
    Thread.setDefaultUncaughtExceptionHandler(handler);
    assertSame(handler, Thread.getDefaultUncaughtExceptionHandler());

    Thread.setDefaultUncaughtExceptionHandler(null);
    assertNull(Thread.getDefaultUncaughtExceptionHandler());
    //TODO add security-based tests
}
 
Example #15
Source File: ForkJoinPool.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: KillRetryTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  driver = createMock(Driver.class);
  storageUtil = new StorageTestUtil(this);
  storageUtil.expectOperations();
  backoffStrategy = createMock(BackoffStrategy.class);
  final ScheduledExecutorService executorMock = createMock(ScheduledExecutorService.class);
  clock = FakeScheduledExecutor.fromScheduledExecutorService(executorMock);
  addTearDown(clock::assertEmpty);
  statsProvider = new FakeStatsProvider();

  Injector injector = Guice.createInjector(
      new LifecycleModule(),
      new PubsubEventModule(),
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(Driver.class).toInstance(driver);
          bind(Storage.class).toInstance(storageUtil.storage);
          bind(ScheduledExecutorService.class).annotatedWith(AsyncExecutor.class)
              .toInstance(executorMock);
          PubsubEventModule.bindSubscriber(binder(), KillRetry.class);
          bind(KillRetry.class).in(Singleton.class);
          bind(BackoffStrategy.class).toInstance(backoffStrategy);
          bind(StatsProvider.class).toInstance(statsProvider);
          bind(UncaughtExceptionHandler.class)
              .toInstance(createMock(UncaughtExceptionHandler.class));
          bind(Executor.class).annotatedWith(AsyncExecutor.class)
              .toInstance(MoreExecutors.directExecutor());
        }
      }
  );
  eventBus = injector.getInstance(EventBus.class);
  PubsubTestUtil.startPubsub(injector);
}
 
Example #17
Source File: ThreadPoolEventTarget.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Override
public void uncaughtException(Thread t, Throwable e) {
  try {
    UncaughtExceptionHandler delegate;
    synchronized (this) {
      delegate = exceptionHandler;
    }
    if (delegate != null) {
      delegate.uncaughtException(t, e);
    }
  } finally {
    logger.error("Event handler threw an exception", e);
  }
}
 
Example #18
Source File: Threads.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method that sets name, daemon status and starts passed thread.
 * @param t thread to frob
 * @param name new name
 * @param handler A handler to set on the thread. Pass null if want to use default handler.
 * @return Returns the passed Thread <code>t</code>.
 */
public static <T extends Thread> T setDaemonThreadRunning(T t, String name,
    UncaughtExceptionHandler handler) {
  t.setName(name);
  if (handler != null) {
    t.setUncaughtExceptionHandler(handler);
  }
  t.setDaemon(true);
  t.start();
  return t;
}
 
Example #19
Source File: AbstractTestDynamicTimeDeadbandActivator.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void setUpException() {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            error = e;
        }
    });
}
 
Example #20
Source File: ThreadTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.lang.Thread#getUncaughtExceptionHandler
 * java.lang.Thread#setUncaughtExceptionHandler
 */
public void test_get_setUncaughtExceptionHandler() {
    class Handler implements UncaughtExceptionHandler {
        public void uncaughtException(Thread thread, Throwable ex) {
        }
    }

    final Handler handler = new Handler();
    Thread.currentThread().setUncaughtExceptionHandler(handler);
    assertSame(handler, Thread.currentThread().getUncaughtExceptionHandler());

    Thread.currentThread().setUncaughtExceptionHandler(null);

    //TODO add security-based tests
}
 
Example #21
Source File: NiFi.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected void setDefaultUncaughtExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread t, final Throwable e) {
            LOGGER.error("An Unknown Error Occurred in Thread {}: {}", t, e.toString());
            LOGGER.error("", e);
        }
    });
}
 
Example #22
Source File: NamingThreadFactory.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@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.isEmpty(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() {
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e);
			}
		});
	}

	return thread;
}
 
Example #23
Source File: ForkJoinPool.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #24
Source File: ForkJoinPool.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: AbstractDependencyManager.java    From status with Apache License 2.0 5 votes vote down vote up
public AbstractDependencyManager(
        @Nullable final String appName,
        @Nullable final Logger logger,
        @Nonnull final ThreadPoolExecutor threadPool,
        @Nonnull final DependencyChecker checker
) {
    this.appName = Strings.isNullOrEmpty(appName) ? getAppName() : appName;
    this.log = null == logger ? Logger.getLogger(getClass()) : logger;

    this.executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
            .setNameFormat("dependency-management-" + MANAGEMENT_THREAD_POOL_COUNT.getAndIncrement() + "-thread-%d")
            .setDaemon(true)
            .setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    log.error("Uncaught throwable in thread " + t.getName() + "/" + t.getId(), e);
                }
            })
            .build()
    );

    this.threadPool = threadPool;

    this.checker = checker;

    VarExporter.forNamespace(getClass().getSimpleName()).includeInGlobal().export(this, "");
}
 
Example #26
Source File: ForkJoinPool.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example #27
Source File: Console.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private static void setupExceptionHandler(final Console console) {
	final UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() {
		public void uncaughtException(Thread thread, Throwable t) {
			try {
				t.printStackTrace();
				Throwable rootCause = rootCauseWithMessage(t);
				JOptionPane.showMessageDialog(console, rootCause.getClass()
						.getName() + ": " + rootCause.getMessage(),
						"Error", ERROR_MESSAGE);
			} catch (final Throwable t2) {
				/*
				 * don't let the Throwable get thrown out, will cause
				 * infinite looping!
				 */
				t2.printStackTrace();
			}
		}

		private Throwable rootCauseWithMessage(Throwable throwable) {
			Throwable cause = throwable;
			for (Iterator<Throwable> causes = Throwables.getCauses(cause); causes
					.hasNext();) {
				Throwable next = causes.next();
				if (next.getMessage() != null) {
					cause = next;
				}
			}
			return cause;
		}

	};
	Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
	System.setProperty(
			"sun.awt.exception.handler", exceptionHandler.getClass().getName()); //$NON-NLS-1$
}
 
Example #28
Source File: JavaHandlerThread.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@CalledByNative
private void listenForUncaughtExceptionsForTesting() {
    mThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            mUnhandledException = e;
        }
    });
}
 
Example #29
Source File: RxJavaCommonPluginsTest.java    From RxJava3-preview with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #30
Source File: jt.java    From letv with Apache License 2.0 5 votes vote down vote up
private void a(Thread thread, Throwable th) {
    for (UncaughtExceptionHandler uncaughtException : c()) {
        try {
            uncaughtException.uncaughtException(thread, th);
        } catch (Throwable th2) {
        }
    }
}