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.apptentive.android.sdk.Apptentive.java

private static void asyncFetchAppConfiguration(final Context context) {
    Thread thread = new Thread() {
        public void run() {
            fetchAppConfiguration(context, GlobalInfo.isAppDebuggable);
        }/*  w w w  .  ja va 2  s  .c  om*/
    };
    Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {
            Log.e("Caught UncaughtException in thread \"%s\"", throwable, thread.getName());
            MetricModule.sendError(context.getApplicationContext(), throwable, null, null);
        }
    };
    thread.setUncaughtExceptionHandler(handler);
    thread.setName("Apptentive-FetchAppConfiguration");
    thread.start();
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProviderService.java

private ExecutorService createExecutor() {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 5, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                private final AtomicInteger counter = new AtomicInteger();
                private final Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
                    @Override/*w  ww  . java2s.  co  m*/
                    public void uncaughtException(Thread t, Throwable e) {
                        log.warn("Error occurred in asynchronous processing ", e);
                    }
                };

                @Override
                public Thread newThread(@Nonnull Runnable r) {
                    Thread thread = new Thread(r, createName());
                    thread.setDaemon(true);
                    thread.setPriority(Thread.MIN_PRIORITY);
                    thread.setUncaughtExceptionHandler(handler);
                    return thread;
                }

                private String createName() {
                    return "oak-lucene-" + counter.getAndIncrement();
                }
            });
    executor.setKeepAliveTime(1, TimeUnit.MINUTES);
    executor.allowCoreThreadTimeOut(true);
    return executor;
}

From source file:com.oltpbenchmark.ThreadBench.java

private void createWorkerThreads() {

    for (Worker worker : workers) {
        worker.initializeState();//w  w w  .  j  av a2s. com
        Thread thread = new Thread(worker);
        thread.setUncaughtExceptionHandler(this);
        thread.start();
        this.workerThreads.add(thread);
    }
    return;
}

From source file:com.baidu.fsg.uid.utils.NamingThreadFactory.java

@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);//from  w  ww.ja v a  2 s .  c o  m
    }
    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;
}

From source file:org.eclipse.eavp.viz.service.csv.CSVPlot.java

/**
 * This operation loads the data that will be plotted. It uses a separate
 * thread to avoid hanging the UI in the event that the file is large. It
 * does not attempt to load the file if the source is null.
 *
 *///from  w  w w. j ava  2 s .c  om
public void load() {

    URI uri = getDataSource();
    if (uri != null) {
        // Only load the file if it is a CSV file.
        final File file = new File(uri);
        if (file.getName().endsWith(".csv")) {
            // Loading has not completed.
            loaded.set(false);

            // Create the loading thread.
            Thread loadingThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    load(file);
                }
            });

            // Force the loading thread to report unhandled exceptions to
            // this thread's exception handler.
            loadingThread.setUncaughtExceptionHandler(Thread.currentThread().getUncaughtExceptionHandler());

            // Start the thread
            loadingThread.start();
        } else {
            logger.error(getClass().getName() + ": Failed to load file " + file.getName()
                    + ", it must be of type .csv");
        }
    }

    return;
}

From source file:com.runwaysdk.dataaccess.database.general.ProcessReader.java

/**
 * Consumes the //from  w  ww.  ja  va 2  s. c  om
 * @param reader
 * @param buffer
 */
private void consumeError(final InputStream inputStream, final StringBuffer buffer) {
    final BufferedReader out = new BufferedReader(new InputStreamReader(inputStream));

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                String line = new String();

                while ((line = out.readLine()) != null) {
                    buffer.append(line);
                }
            } catch (Throwable t) {
                String msg = "Error when consuming the error stream.";
                throw new ProgrammingErrorException(msg, t);
            }
        }
    }, ERROR_THREAD);

    t.setUncaughtExceptionHandler(this);
    t.setDaemon(true);
    t.start();
}

From source file:com.runwaysdk.dataaccess.database.general.ProcessReader.java

/**
 * Consumes the output of the process in a separate thread.
 * /*from w  w  w .  j a  va 2  s .c  om*/
 * @param inputStream
 * @param stream
 */
private void consumeOutput(final InputStream inputStream, final PrintStream stream) {
    final BufferedReader out = new BufferedReader(new InputStreamReader(inputStream));

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                String line = new String();

                while ((line = out.readLine()) != null) {
                    stream.println(line);
                }

                stream.close();
            } catch (Throwable t) {
                String msg = "Error when consuming the process output.";
                throw new ProgrammingErrorException(msg, t);
            }
        }
    }, OUTPUT_THREAD);

    t.setUncaughtExceptionHandler(this);
    t.setDaemon(true);
    t.start();
}

From source file:com.runwaysdk.dataaccess.database.general.ProcessReader.java

private void _start(boolean async) {
    Thread t = new Thread(new Runnable() {

        @Override/*ww w. j a v a  2  s  .c  o  m*/
        public void run() {
            try {
                ProcessReader.this.process = ProcessReader.this.builder.start();

                consumeOutput(process.getInputStream(), ProcessReader.this.output);
                consumeError(process.getErrorStream(), ProcessReader.this.errorOut);

                ProcessReader.this.process.waitFor();
            } catch (Throwable ex) {
                throw new ProgrammingErrorException(ProcessReader.this.toString(), ex);
            }
        }
    }, PROCESS_THREAD);

    t.setUncaughtExceptionHandler(this);
    t.start();

    if (!async) {
        // block this thread until everything is done
        try {
            t.join();
        } catch (InterruptedException e) {
            log.error(e);
        }
    }
}

From source file:edu.unc.lib.deposit.fcrepo3.IngestDepositTest.java

@Test
public void testRunFailObjectIngest() throws Exception {

    when(client.ingestRaw(any(byte[].class), any(Format.class), anyString())).thenReturn(new PID("pid"))
            .thenReturn(new PID("pid")).thenThrow(new FedoraException(""));

    Thread jobThread = new Thread(job);
    final boolean[] exceptionCaught = new boolean[] { false };
    Thread.UncaughtExceptionHandler jobFailedHandler = new Thread.UncaughtExceptionHandler() {
        @Override//  w  w w  .j  a va  2s .co m
        public void uncaughtException(Thread th, Throwable ex) {
            if (ex instanceof JobFailedException)
                exceptionCaught[0] = true;
        }
    };

    jobThread.setUncaughtExceptionHandler(jobFailedHandler);
    jobThread.start();

    // Start processing with a timelimit to prevent infinite wait in case of failure
    jobThread.join();

    // Only the one successful top level pid added because of ordering
    verify(client).addObjectRelationship(any(PID.class), anyString(), any(PID.class));

    // Failing on third ingestRaw
    verify(client, times(3)).ingestRaw(any(byte[].class), any(Format.class), anyString());

    // Only one object with data should have been uploaded
    verify(client).upload(any(File.class));

    // PREMIS was written
    verify(client, times(0)).writePremisEventsToFedoraObject(any(PremisEventLogger.class), any(PID.class));

    assertTrue("Job must have been registered", jmsListener.registeredJob);
    assertTrue("Job must have been unregistered on failure", jmsListener.registeredJob);

    assertTrue("Exception must have been thrown by job", exceptionCaught[0]);

}

From source file:eu.sisob.uma.NPL.Researchers.GateDataExtractorTask.java

/**
 *
 *///from   ww  w  . j  a  v  a2s.  c  o  m
@Override
public void executeTask() {
    if (getExecutorResource() != null) {

        TextMiningParserGateResearcher parser = null;
        DataRepository parserRepPrePro = null;
        RepositoryProcessedDataXML repXML = null;

        try {
            //Take parser and load input repository from CSV                    
            parser = (TextMiningParserGateResearcher) this.executorResource.getResource();
            parserRepPrePro = (DataRepository) parser.getRepOutput();
            repXML = (RepositoryProcessedDataXML) parser.getRepInput();

            List<MiddleData> mds = null;
            while ((mds = taskRepPrePro.getData(DataExchangeLiterals.ID_TEXTMININGPARSER_GATERESEARCHER, 100))
                    .size() > 0) {
                for (MiddleData md : mds)
                    parserRepPrePro.addData(md);
            }

            Thread th = null;
            UncaughtExceptionHandler he = new UncaughtExceptionHandler() {
                public Throwable e = null;

                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    occursUncaugthExceptionInGateProcess = true;
                    ProjectLogger.LOGGER.info("uncaughtException: " + e.getMessage());
                }
            };

            //Launch GATE parser     
            this.occursUncaugthExceptionInGateProcess = false;
            th = new Thread(parser);
            th.setUncaughtExceptionHandler(he);
            th.start();
            th.join();

            this.xml_doc_results = (Document) repXML.getDocXML().clone();

            // Augmented Information Block
            if (this.use_dataresolver && this.credentials_academic_trad_tables != null) {
                //Using data resolver "method 2", see the class for the heuristic

                try {
                    DataResearcherAugmentedInformation.resolveLocationOfEntities(xml_doc_results,
                            new LocationDataResolver_Method2(true, this.credentials_dataresolver));
                } catch (Exception ex) {
                    Logger.getRootLogger().error("Error resolving locator. " + ex.toString());
                }

            }

            // Augmented Information Block
            if (this.use_academic_trad_tables && this.credentials_academic_trad_tables != null) {
                //Using data resolver "method 2", see the class for the heuristic                        
                //DataResearcherAugmentedInformation.resolveLocationOfEntities(xml_doc_results, 
                //new LocationDataResolver_Method2(true, this.credentials_academic_trad_tables));                       

                H2DBPool dbpool_academic_trad_tables = new H2DBPool(credentials_academic_trad_tables);
                try {
                    DataResearcherAugmentedInformation.resolveAcademicPosistion(xml_doc_results,
                            dbpool_academic_trad_tables);
                } catch (Exception ex) {
                    Logger.getRootLogger().error("Error academic positions. " + ex.toString());
                }
            }
        } catch (Exception ex) {
            ProjectLogger.LOGGER.error(ex.getMessage());
        } finally {
            if (this.occursUncaugthExceptionInGateProcess) {
                if (parser != null) {
                    ProjectLogger.LOGGER.info("Begin reload GATE parser because succeded a uncaughtException!");
                    try {
                        parser.endActions();
                        parser.iniActions();
                    } catch (Exception ex) {
                        ProjectLogger.LOGGER.error(null, ex);
                    }
                    ProjectLogger.LOGGER.info("Done!");
                }
            }

            if (parserRepPrePro != null)
                parserRepPrePro.clearData();

            if (repXML != null)
                repXML.clearData();
        }
    } else {
        ProjectLogger.LOGGER.info(this.iaux + " can't get GATE Data Extractor resource");
        this.xml_doc_results = null;
    }
}