Example usage for java.lang Thread setUncaughtExceptionHandler

List of usage examples for java.lang Thread setUncaughtExceptionHandler

Introduction

In this page you can find the example usage for java.lang Thread setUncaughtExceptionHandler.

Prototype

public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) 

Source Link

Document

Set the handler invoked when this thread abruptly terminates due to an uncaught exception.

Usage

From source file:com.hellblazer.jackal.configuration.ThreadConfig.java

@Bean(name = "communicationsDispatchers")
@Primary/*from   w w w  .  ja v  a2 s  .  c om*/
@Autowired
public ExecutorService communicationsDispatchers(Identity partitionIdentity) {
    final int id = partitionIdentity.id;
    return Executors.newCachedThreadPool(new ThreadFactory() {
        int count = 0;

        @Override
        public Thread newThread(Runnable target) {
            Thread t = new Thread(target,
                    String.format("Communications Dispatcher[%s] for node[%s]", count++, id));
            t.setDaemon(true);
            t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    log.error(String.format("Exception on %s", t), e);
                }
            });
            return t;
        }
    });
}

From source file:edu.umn.msi.tropix.common.io.impl.AsyncStreamCopierImplTest.java

@Test(groups = "unit", timeOut = 1000, invocationCount = 10)
public void close() throws IOException, InterruptedException {
    final AsyncStreamCopierImpl copier = new AsyncStreamCopierImpl();
    final Reference<Thread> threadReference = new Reference<Thread>();
    final Reference<Throwable> throwableReference = new Reference<Throwable>();
    copier.setExecutor(new Executor() {
        public void execute(final Runnable runnable) {
            final Thread thread = new Thread(runnable);
            threadReference.set(thread);
            thread.start();/*ww  w .  j  a v a  2  s  . c  o  m*/
            thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                public void uncaughtException(final Thread arg0, final Throwable throwable) {
                    throwableReference.set(throwable);
                }
            });
        }
    });
    final PipedOutputStream pipedOutputStream = new PipedOutputStream();
    final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
    final ByteArrayOutputStream copiedStream = new ByteArrayOutputStream();
    copier.copy(pipedInputStream, copiedStream, true);
    Thread.sleep(3);
    assert new String(copiedStream.toByteArray()).equals("");
    pipedOutputStream.write("Hello ".getBytes());
    pipedOutputStream.flush();
    while (!new String(copiedStream.toByteArray()).equals("Hello ")) {
        Thread.sleep(1);
    }
    pipedOutputStream.write("World!".getBytes());
    pipedOutputStream.flush();
    while (!new String(copiedStream.toByteArray()).equals("Hello World!")) {
        Thread.sleep(1);
    }
    assert threadReference.get().isAlive();
    pipedOutputStream.close();
    while (threadReference.get().isAlive()) {
        Thread.sleep(1);
    }
    assert throwableReference.get() == null;
}

From source file:org.rhq.core.pc.util.LoggingThreadFactory.java

/**
 * @see java.util.concurrent.ThreadFactory#newThread(Runnable)
 *///ww w . ja v a2  s  .c  o  m
public Thread newThread(Runnable r) {
    Thread t = new Thread(group, r, poolName + "-" + threadNumber.getAndIncrement());

    t.setDaemon(this.daemon);

    if (t.getPriority() != Thread.NORM_PRIORITY) {
        t.setPriority(Thread.NORM_PRIORITY);
    }

    t.setUncaughtExceptionHandler(this);

    return t;
}

From source file:org.netflux.core.task.AbstractTask.java

public void start() {
    // TODO: Thread handling
    // TODO: Improve uncaught exception handling
    Thread taskWorker = this.getTaskWorker();
    taskWorker.setName(this.getName());
    taskWorker.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable throwable) {
            String message = MessageFormat
                    .format(AbstractTask.messages.getString("exception.uncaught.exception"), thread.getName());
            AbstractTask.log.error(message, throwable);
            for (OutputPort outputPort : AbstractTask.this.outputPorts.values()) {
                outputPort.consume(Record.END_OF_DATA);
            }//from   www . j a  v a2 s. c  om
        }
    });
    taskWorker.start();
}

From source file:com.thoughtworks.go.server.service.ConfigSaveDeadlockDetectionIntegrationTest.java

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();//from  w ww.j  a  va 2 s.  co m
            throw new RuntimeException(e.getMessage(), e);
        }
    });
    return thread;
}

From source file:org.hibernate.search.test.performance.scenario.TestExecutor.java

private ExecutorService newAutoStoppingErrorReportingThreadPool(TestScenarioContext ctx) {
    int nThreads = ctx.testContext.threadCount;
    ThreadFactory threadFactory = new SearchThreadFactory(ctx.scenario.getClass().getSimpleName()) {
        @Override//from   w w w.j  a  va 2 s  .  com
        public Thread newThread(Runnable r) {
            Thread t = super.newThread(r);
            // Just ignore uncaught exceptions, we'll report them through other means (see below)
            t.setUncaughtExceptionHandler((thread, throwable) -> {
            });
            return t;
        }
    };
    return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
            threadFactory) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);
            if (t != null) {
                ctx.reportFailure(t);
                shutdown();
            }
        }
    };
}

From source file:org.apache.james.blob.objectstorage.AESPayloadCodec.java

@Override
public Payload write(InputStream is) {
    PipedInputStream snk = new PipedInputStream();
    try {//from w  ww  .  j  a  va 2 s .c  om
        PipedOutputStream src = new PipedOutputStream(snk);
        OutputStream outputStream = streamingAead.newEncryptingStream(src,
                PBKDF2StreamingAeadFactory.EMPTY_ASSOCIATED_DATA);
        Thread copyThread = new Thread(() -> {
            try (OutputStream stream = outputStream) {
                IOUtils.copy(is, stream);
            } catch (IOException e) {
                throw new RuntimeException("Stream copy failure ", e);
            }
        });
        copyThread.setUncaughtExceptionHandler(
                (Thread t, Throwable e) -> LOGGER.error("Unable to encrypt payload's input stream", e));
        copyThread.start();
        return Payloads.newInputStreamPayload(snk);
    } catch (IOException | GeneralSecurityException e) {
        throw new RuntimeException("Unable to build payload for object storage, failed to " + "encrypt", e);
    }
}

From source file:com.adaptris.core.jms.ActiveJmsConnectionErrorHandler.java

@Override
public void init() throws CoreException {
    super.init();
    try {/*from   w  ww  .j av  a2s.  co m*/
        MyExceptionHandler handler = new MyExceptionHandler();
        CountDownLatch verifierThreadGate = new CountDownLatch(1);
        verifier = new JmsConnectionVerifier(idForLogging, verifierThreadGate);
        Thread verifierThread = new ManagedThreadFactory(getClass().getSimpleName()).newThread(verifier);
        verifierThread.setName("JmsConnectionErrorHandler for " + idForLogging);
        verifierThread.setUncaughtExceptionHandler(handler);
        verifierThread.start();
        boolean actuallyStarted = verifierThreadGate.await(DEFAULT_MAX_WAIT_FOR_START.toMilliseconds(),
                TimeUnit.MILLISECONDS);
        if (!actuallyStarted) {
            if (handler.hasError()) {
                ExceptionHelper.rethrowCoreException(handler.lastCaughtException);
            } else {
                throw new CoreException("Failed to start connection error handler");
            }
        }
        if (additionalLogging()) {
            log.debug("ActiveJmsConnectionErrorHandler for {} started", idForLogging);
        }
    } catch (Exception e) {
        ExceptionHelper.rethrowCoreException(e);
    }
}

From source file:org.akubraproject.tck.AbstractTests.java

protected Thread doInThread(Runnable r, final boolean[] failed) throws Exception {
    Thread t = new Thread(r, "TCKTest");

    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            if (failed != null) {
                synchronized (failed) {
                    failed[0] = true;/* w ww  . ja  v a  2  s. c o m*/
                }
            }

            e.printStackTrace();
        }
    });

    t.start();
    return t;
}

From source file:de.micromata.mgc.javafx.launcher.gui.AbstractMainWindow.java

@Override
public void initializeWithModel() {
    Thread currentThread = Thread.currentThread();
    currentThread.setUncaughtExceptionHandler(model.getUncaughtExceptionHandler());
    addCss();//from www  .j a va2 s .co m
    LauncherLocalSettingsConfigModel config = MgcLauncher.getLauncherConfig();
    if (config.isEnableLF5() == false) {
        launchMenu.setVisible(false);
    }
    if (SystemService.get().getOsType() != OsType.Windows) {
        hideWindowMenu.setVisible(false);
    }
    stage.setOnCloseRequest(event -> {
        if (SystemService.get().getOsType() != OsType.Windows) {
            event.consume();

            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle(model.getTranslateService().translate("mgc.launcher.gui.quitconfirmation.title"));
            alert.setHeaderText(
                    model.getTranslateService().translate("mgc.launcher.gui.quitconfirmation.header"));
            alert.setContentText(
                    model.getTranslateService().translate("mgc.launcher.gui.quitconfirmation.message"));
            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == ButtonType.OK) {
                closeApplication(null);
            }
        }
    });

    startServerButton.setOnAction(e -> {
        startServer();
    });
    stopServerButton.setOnAction(e -> {
        stopServer();
    });
    stopServerButton.setDisable(true);
    boolean runnin = MgcLauncher.get().getApplication().isRunning();
    startServerButton.setDisable(runnin);
    stopServerButton.setDisable(runnin == false);
    openBrowser.setDisable(runnin == false);
    addStartServerEventHandler();
    addStopServerEventHandler();

    openBrowser.setOnAction(e -> {
        launchBrowser();
    });
    loggingPane.widthProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth,
                Number newSceneWidth) {
            loggingController.adjustWidth(newSceneWidth.doubleValue());
        }
    });
    loggingPane.heightProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth,
                Number newSceneWidth) {
            loggingController.adjustHeight(newSceneWidth.doubleValue());
        }
    });
    loggingController.adjustHeight(loggingPane.getHeight());
    loggingController.adjustWidth(loggingPane.getWidth());
    MgcEventRegistries.getEventInstanceRegistry()
            .registerListener(new MgcApplicationStartStopToEventListener());
    String helpUrl = getModel().getApplicationInfo().getHelpUrl();
    if (StringUtils.isBlank(helpUrl) == true) {
        helpButton.setVisible(false);
    } else {
        helpButton.setOnAction(event -> {
            SystemService.get().openUrlInBrowser(helpUrl);
        });
    }
    FXEvents.get().addEventHandler(this, stopServerButton, MgcLauncherEvent.APP_STARTED, event -> {

        if (config.isStartBrowserOnStartup() == true) {
            launchBrowser();
        }
    });
}