/** * Creates a new thread. * * @param r The runnable task. */ public Thread newThread(Runnable r) { Thread result = new Thread(r); result.setName("Restlet-" + result.hashCode()); result.setUncaughtExceptionHandler(new LoggingExceptionHandler()); result.setDaemon(this.daemon); return result; }
@Override public Thread newThread(Runnable r) { Thread t = defaultFactory.newThread(r); t.setUncaughtExceptionHandler(handler); t.setDaemon(true); // daemonize the thread return t; }
@Override protected void cleanUpExamples(int epoch) { // int n=0; for (int k = 0; k < nthreads; k++) { if (currentTrainingRun.queues.get(k).size() > 0) { // n++; TrainerThread t = new TrainerThread(currentTrainingRun.queues.get(k), k); Thread th = new Thread(t, "xthread " + k); th.setDaemon(true); th.setUncaughtExceptionHandler(t); if (log.isDebugEnabled()) log.debug("Starting thread " + k); currentTrainingRun.threads.add(th); th.start(); } } while (currentTrainingRun.threads.size() > 0) { try { Thread th = currentTrainingRun.threads.get(0); if (log.isDebugEnabled()) log.debug("Joining thread " + th.getName()); th.join(); // will finish adding any new threads in uncaughtexceptionhandlers before // returning currentTrainingRun.threads.remove(0); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } currentTrainingRun.threads = null; }
@Override public void uncaughtException(Thread t, Throwable thrw) { // log warning for the exception StringWriter s = new StringWriter(); s.write("Uncaught exception in thread " + t.getName() + ":\n"); PrintWriter w = new PrintWriter(s); thrw.printStackTrace(w); log.warn(s.toString()); try { s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // resume work Thread th = new Thread(this, "Rxthread " + this.id); th.setDaemon(true); th.setUncaughtExceptionHandler(this); synchronized (currentTrainingRun.threads) { log.warn("Resuming thread " + t.getName() + " with " + th.getName()); currentTrainingRun.threads.add(th); // don't want to join before thread has been started th.start(); } }
public void onRemovePressed(final ContributedLibrary lib) { boolean managedByIndex = indexer.getIndex().getLibraries().contains(lib); if (!managedByIndex) { int chosenOption = JOptionPane.showConfirmDialog(this, _("This library is not listed on Library Manager. You won't be able to resinstall it from here.\nAre you sure you want to delete it?"), _("Please confirm library deletion"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (chosenOption != JOptionPane.YES_OPTION) { return; } } clearErrorMessage(); installerThread = new Thread(new Runnable() { @Override public void run() { try { setProgressVisible(true, _("Removing...")); installer.remove(lib); onIndexesUpdated(); // TODO: Do a better job in refreshing only the needed element //getContribModel().updateLibrary(lib); } catch (Exception e) { throw new RuntimeException(e); } finally { setProgressVisible(false, ""); } } }); installerThread.setUncaughtExceptionHandler(new InstallerJDialogUncaughtExceptionHandler(this, noConnectionErrorMessage)); installerThread.start(); }
/** * @param thread the thread the task is running on * @param runnable the <code>Retriever</code> running on the thread * @throws IllegalArgumentException if either <code>thread</code> or <code>runnable</code> is * null */ @Override protected void beforeExecute(Thread thread, Runnable runnable) { if (thread == null) { String msg = Logging.getMessage("nullValue.ThreadIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } if (runnable == null) { String msg = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } RetrievalTask task = (RetrievalTask) runnable; task.retriever.setBeginTime(System.currentTimeMillis()); if (DownloaderRetrievalService.this.activeTasks.contains(task)) { // Task is a duplicate Logging.logger() .finer( Logging.getMessage( "BasicRetrievalService.CancellingDuplicateRetrieval", task.getRetriever().getName())); task.cancel(true); } DownloaderRetrievalService.this.activeTasks.add(task); thread.setName(RUNNING_THREAD_NAME_PREFIX + task.getRetriever().getName()); thread.setPriority(Thread.MIN_PRIORITY); // Subordinate thread priority to rendering thread.setUncaughtExceptionHandler(DownloaderRetrievalService.this); super.beforeExecute(thread, runnable); }
@Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler()); System.out.println("thread-id:" + thread.getId()); return thread; }
private void run( Runnable runnable, int numberOfRequests, final ConcurrentHashMap<String, Boolean> results) throws InterruptedException { Boolean finalResult = true; LOGGER.info("Tests start now!"); final ArrayList<Thread> threads = new ArrayList<>(); for (int i = 0; i < numberOfRequests; i++) { Thread t = new Thread(runnable, "pipeline" + i); threads.add(t); } for (Thread t : threads) { Thread.sleep(1000 * (new Random().nextInt(3) + 1)); t.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOGGER.error("Exception " + e + " from thread " + t); results.put(t.getName(), false); } }); t.start(); } for (Thread t : threads) { int i = threads.indexOf(t); if (i == (numberOfRequests - 1)) { // takeHeapDump(dumpDir, i); } t.join(); } for (String threadId : results.keySet()) { finalResult = results.get(threadId) && finalResult; } assertThat(finalResult, is(true)); }
public static void main(String[] args) { // 建立异常处理者 ThreadExceptionHandler handler = new ThreadExceptionHandler(); ThreadGroup threadGroup1 = new ThreadGroup("group1"); Atom atom = new Atom(null, null, null); FutureTask<Object> transMgr = new FutureTask<Object>(atom); Thread t = new Thread(threadGroup1, transMgr); // 这是匿名类写法 Thread thread1 = // 这个线程是threadGroup1的一员 new Thread( threadGroup1, new Runnable() { public void run() { // 抛出unchecked异常 throw new RuntimeException("测试异常"); } }); // 设置异常处理者 thread1.setUncaughtExceptionHandler(handler); thread1.start(); System.out.println(121221); }
/** Return a thread. */ @Override public Thread newThread(Runnable r) { if (shutdown) return null; Runnable wrapper = new Runnable() { /** Keep track of non-daemon threads so shutdown can wait for their termination. */ @Override public void run() { threads.fromNewToRunning(Thread.currentThread()); r.run(); /* If the task has thrown an exception, the code below is * not getting executed. The uncaughtException this.handler * removes the thread from the tracker list and notifies * the completer. */ threads.removeRunning(Thread.currentThread()); if (!hasActiveNonDaemonThreads()) completer.accept(ThreadFactoryTracker.this, null); } }; Thread t = factory.newThread(wrapper); t.setName(t.getName() + "-" + threadName); t.setUncaughtExceptionHandler(handler); threads.addNew(t); return t; }
@Override public void init() throws CoreException { String loggingId = retrieveConnection(AdaptrisConnection.class).getUniqueId(); if (!isEmpty(loggingId)) { idForLogging = loggingId; } else { idForLogging = abbreviate(retrieveConnection(JmsConnection.class).getBrokerDetailsForLogging(), 20); } try { String s = "MockJmsConnectionErrorHandler"; final String idForLogging = abbreviate(s, 20); MyExceptionHandler handler = new MyExceptionHandler(); verifier = new MockJmsConnectionVerifier(idForLogging, new CountDownLatch(1)); if (callback != null) { callback.register(verifier); } Thread verifierThread = new Thread(verifier); verifierThread.setUncaughtExceptionHandler(handler); verifierThread.start(); if (additionalLogging()) { log.debug("ActiveJmsConnectionErrorHandler for " + idForLogging + " started"); } } catch (Exception e) { throw new CoreException(e); } }
@Test public void test() throws Exception { MmsClient c = createAndConnect(); new Thread( () -> { while (received.size() < NUMBER_OF_MESSAGES) { rndSleep(300, TimeUnit.MILLISECONDS); t.closeIt(); } }) .start(); final AtomicInteger ack = new AtomicInteger(); Runnable server = new Runnable() { public void run() { int latestId = 0; Integer ackIt = null; while (received.size() < NUMBER_OF_MESSAGES) { Message tm = t.take(Message.class); if (tm instanceof Broadcast) { Broadcast bs = (Broadcast) tm; try { BroadcastTestMessage hw = (BroadcastTestMessage) MmsMessage.tryRead(bs); int id = hw.getId(); assertEquals(latestId++, id); received.add(id); } catch (Exception e) { e.printStackTrace(); } ackIt = null; } else { if (ackIt == null) { ackIt = ThreadLocalRandom.current().nextInt(ack.get(), latestId + 1); } ack.set(ackIt); latestId = ackIt; t.send(new Connected().setSessionId(BIN1).setLastReceivedMessageId((long) ackIt)); } } } }; Thread t = new Thread(server); t.setUncaughtExceptionHandler((a, b) -> b.printStackTrace()); t.start(); for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { Thread.sleep(ThreadLocalRandom.current().nextLong(10)); c.broadcast(new BroadcastTestMessage().setId(i)); } while (received.size() < NUMBER_OF_MESSAGES) { Thread.sleep(10); } }
/** * start gvim with args using a ProcessBuilder and setup {@link #vc VimConnection} . * * @param args */ private void start(String workingDir, boolean embedded, boolean tabbed, String... args) { if (!tabbed && vc != null && vc.isServerRunning()) { return; } VimPlugin plugin = VimPlugin.getDefault(); if (vc == null || !vc.isServerRunning()) { vc = new VimConnection(ID); t = new Thread(vc); t.setUncaughtExceptionHandler(new VimExceptionHandler()); t.setDaemon(true); t.start(); } try { logger.debug("Trying to start vim"); logger.debug(Arrays.toString(args)); ProcessBuilder builder = new ProcessBuilder(args); /*java.util.Map<String, String> env = builder.environment(); env.put("SPRO_GVIM_DEBUG", "/tmp/netbeans.log"); env.put("SPRO_GVIM_DLEVEL", "0xffffffff");*/ if (workingDir != null) { builder.directory(new File(workingDir)); } p = builder.start(); logger.debug("Started vim"); } catch (IOException e) { logger.error("error:", e); } // Waits until server starts.. vim should return startupDone long maxTime = System.currentTimeMillis() + 10000L; // 10 seconds while (!vc.isServerRunning()) { if (System.currentTimeMillis() >= maxTime) { try { vc.close(); } catch (Exception e) { logger.error("error:", e); } String message = plugin.getMessage("gvim.startup.failed", plugin.getMessage("gvim.startupDone.event")); throw new RuntimeException(message); } // sleep so that we don't have a messy cpu-hogging infinite loop // here long stoptime = 2000L; // 2 Seconds logger.debug("Waiting to connect to vim server"); try { Thread.sleep(stoptime); } catch (InterruptedException e) { e.printStackTrace(); } } this.embedded = embedded; }
@Override public Thread newThread(Runnable r) { Thread t = new Thread( r, String.format("webcam-panel-scheduled-executor-%d", number.incrementAndGet())); t.setUncaughtExceptionHandler(WebcamExceptionHandler.getInstance()); t.setDaemon(true); return t; }
/** * Handles each person of the given <code>population</code> with a AbstractPersonAlgorithm * provided by <code>algoProvider</code>, using up to <code>numberOfThreads</code> threads to * speed things up. This method will request a new instance of the AbstractPersonAlgorithm for * each thread it allocates, thus enabling the parallel use of non-thread-safe algorithms. For * thread-safe algorithms, {@link #run(Population, int, AbstractPersonAlgorithm)} may be an easier * method to use. * * @param population * @param numberOfThreads * @param algoProvider */ public static void run( final Population population, final int numberOfThreads, final PersonAlgorithmProvider algoProvider) { int numOfThreads = Math.max( numberOfThreads, 1); // it should be at least 1 here; we allow 0 in other places for "no threads" PersonAlgoThread[] algoThreads = new PersonAlgoThread[numOfThreads]; Thread[] threads = new Thread[numOfThreads]; String name = null; Counter counter = null; final AtomicBoolean hadException = new AtomicBoolean(false); final ExceptionHandler uncaughtExceptionHandler = new ExceptionHandler(hadException); // setup threads for (int i = 0; i < numOfThreads; i++) { PersonAlgorithm algo = algoProvider.getPersonAlgorithm(); if (i == 0) { name = algo.getClass().getSimpleName(); counter = new Counter("[" + name + "] handled person # "); } PersonAlgoThread algothread = new PersonAlgoThread(algo, counter); Thread thread = new Thread(algothread, name + "." + i); thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); threads[i] = thread; algoThreads[i] = algothread; } // distribute workload between threads, as long as threads are not yet started, so we don't need // synchronized data structures int i = 0; for (Person person : population.getPersons().values()) { algoThreads[i % numOfThreads].handlePerson(person); i++; } // start the threads for (Thread thread : threads) { thread.start(); } // wait for the threads to finish try { for (Thread thread : threads) { thread.join(); } counter.printCounter(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (hadException.get()) { throw new RuntimeException( "Exception while processing persons. Cannot guarantee that all persons have been fully processed."); } }
@Override public Thread newThread(Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setName(name + "-" + count.incrementAndGet()); if (exceptionHandler != null) { thread.setUncaughtExceptionHandler(exceptionHandler); } return thread; }
@Override public Thread newThread(Runnable runnable) { Thread thread = _threadFactory.newThread(runnable); thread.setUncaughtExceptionHandler(_recordUncaughtExceptionHandler); _createdThreads.add(thread); return thread; }
@Override public Thread newThread(final Runnable adapter) { assert null != adapter : "Parameter 'adapter' of method 'newThread' must not be null"; final Thread thread = new Thread(adapter); thread.setName("Feature Adapter"); thread.setPriority(Thread.MIN_PRIORITY); thread.setUncaughtExceptionHandler(this); return thread; }
/** * Create a new thread * * @param name The name of the thread * @param runnable The work for the thread to do * @param daemon Should the thread block JVM shutdown? * @return The unstarted thread */ public static Thread newThread(String name, Runnable runnable, Boolean daemon) { Thread thread = new Thread(runnable, name); thread.setDaemon(daemon); thread.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { log.error("Uncaught exception in thread '" + t.getName() + "':", e); } }); return thread; }
private Thread createThread(Runnable runnable, String name) throws InterruptedException { Thread thread = new Thread(runnable, name); thread.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { e.printStackTrace(); throw new RuntimeException(e.getMessage(), e); } }); return thread; }
@Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, QUERY_POOL_NAME + "-" + suffix.incrementAndGet()); thread.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOGGER.error("UNCAUGHT exception in thread " + t.getName(), e); } }); return thread; }
public void connect(SocketChannelHandler handler) { this.handler = handler; consumer.setUncaughtExceptionHandler( new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { log.warn(String.format("Uncaught exception on %s", t), e); } }); consumer.setDaemon(true); consumer.start(); fsm.connect(); }
public void onReady(ReadyEvent event) { log("Setting up api related config..."); Thread t = new Thread( () -> { TagCommand.initTags(event.getJDA(), logger); PublicLog.init(api, logger::logThrowable); this.api = event.getJDA(); if (config.has("home")) home = api.getGuildById(config.getString("home")); new ModLogManager(api); User uOwner = api.getUserById(owner); try { log("Owner: " + uOwner.getUsername() + "#" + uOwner.getDiscriminator()); } catch (NullPointerException e) { logger.logThrowable( new NullPointerException( "Owner could not be retrieved from the given id. Do you share a guild with this bot? - Caused by id: \"" + owner + "\"")); } this.handler.setApi(event.getJDA()); try { initCommands(api); } catch (UnknownHostException | UnsupportedDataTypeException e) { logger.logThrowable(e); } AccountSettings as = new AccountSettings(console); console.setAccountSettings(as); as.setApi(api); if (audio) api.addEventListener(new MinnAudioManager()); console.setTitle( api.getSelfInfo().getUsername() + "#" + api.getSelfInfo() .getDiscriminator()); // so you know which one is logged in! inviteurl = getInviteUrl(); tmp.init(this); logger.logInfo("Setup completed."); }); t.setDaemon(false); t.setPriority(Thread.MAX_PRIORITY); t.setName("onReady..."); t.setUncaughtExceptionHandler((Thread.UncaughtExceptionHandler) logger); t.start(); }
/** * Main method of the example. Initialize a Thread to process the uncaught exceptions and starts a * Task object that always throws an exception * * @param args */ public static void main(String[] args) { // Creates the Task Task task = new Task(); // Creates the Thread Thread thread = new Thread(task); // Sets de uncaugh exceptio handler thread.setUncaughtExceptionHandler(new ExceptionHandler()); // Starts the Thread thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Thread has finished\n"); }
/** * <a href="https://issues.apache.org/jira/browse/WICKET-3769">WICKET-3769</a> * * @throws Exception */ @Test public void applicationAndSessionAreExported() throws Exception { // bind the session so it can be found in TestSessionFilter tester.getSession().bind(); // execute TestSessionFilter in different thread so that the Application and the Session are // not set by WicketTester Thread testThread = new Thread( new Runnable() { public void run() { try { TestSessionFilter sessionFilter = new TestSessionFilter(tester); Assert.assertFalse(Application.exists()); Assert.assertFalse(Session.exists()); sessionFilter.doFilter( tester.getRequest(), tester.getResponse(), new TestFilterChain()); Assert.assertFalse(Application.exists()); Assert.assertFalse(Session.exists()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } }); final StringBuilder failMessage = new StringBuilder(); final AtomicBoolean passed = new AtomicBoolean(true); testThread.setUncaughtExceptionHandler( new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { failMessage.append(e.getMessage()); passed.set(false); } }); testThread.start(); testThread.join(Duration.seconds(1).getMilliseconds()); Assert.assertTrue(failMessage.toString(), passed.get()); }
/** * Initializes the specified thread. This method is called by {@link #newThread(Runnable)} after a * new thread has been obtained from the wrapped thread factory. It initializes the thread * according to the options set for this factory. * * @param t the thread to be initialized */ private void initializeThread(final Thread t) { if (getNamingPattern() != null) { final Long count = Long.valueOf(threadCounter.incrementAndGet()); t.setName(String.format(getNamingPattern(), count)); } if (getUncaughtExceptionHandler() != null) { t.setUncaughtExceptionHandler(getUncaughtExceptionHandler()); } if (getPriority() != null) { t.setPriority(getPriority().intValue()); } if (getDaemonFlag() != null) { t.setDaemon(getDaemonFlag().booleanValue()); } }
private Context run( ClassLoader classLoader, final String classpath, final String mainClass, final String[] args, final Properties properties) { Properties contextProperties = new Properties(); contextProperties.putAll(commonSystemProperties); contextProperties.putAll(properties); final Context context = new Context(classLoader, contextProperties); Thread thread = new Thread() { @Override public void run() { currentContext.set(context); context.setProperty("java.class.path", classpath); try { runMain(loadClass(mainClass), args); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (MainClassNotFoundException e) { context.setException(e); } catch (Throwable e) { getUncaughtExceptionHandler().uncaughtException(this, e); } } }; context.setMainThread(thread); thread.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { context.setException(e); } }); thread.setContextClassLoader(classLoader); thread.start(); return context; }
public void onInstallPressed(final ContributedLibrary lib, final ContributedLibrary replaced) { clearErrorMessage(); installerThread = new Thread(new Runnable() { @Override public void run() { try { setProgressVisible(true, _("Installing...")); installer.install(lib, replaced); onIndexesUpdated(); // TODO: Do a better job in refreshing only the needed element //getContribModel().updateLibrary(lib); } catch (Exception e) { throw new RuntimeException(e); } finally { setProgressVisible(false, ""); } } }); installerThread.setUncaughtExceptionHandler(new InstallerJDialogUncaughtExceptionHandler(this, noConnectionErrorMessage)); installerThread.start(); }
@Override protected void onUpdatePressed() { super.onUpdatePressed(); installerThread = new Thread(new Runnable() { @Override public void run() { try { setProgressVisible(true, ""); installer.updateIndex(); onIndexesUpdated(); } catch (Exception e) { throw new RuntimeException(e); } finally { setProgressVisible(false, ""); } } }); installerThread.setUncaughtExceptionHandler(new InstallerJDialogUncaughtExceptionHandler(this, noConnectionErrorMessage)); installerThread.start(); }
@Override public void frameBufferUpdateRequest( final RFBClient client, boolean incremental, int x, int y, int w, int h) throws IOException { // TODO Auto-generated method stub // host.getWindow().getDecorView().getViewTreeObserver().removeOnPreDrawListener(this); // host.getWindow().getDecorView().getViewTreeObserver().addOnPreDrawListener(this); // updateAttempts = 3; // sendWholeScreen(client); Thread t = new Thread() { @Override public void run() { while (true) { try { sendWholeScreen(client); Thread.sleep(40); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; t.setName("loop update thread"); t.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { // TODO Auto-generated method stub // thread.start(); } }); t.start(); }