Example usage for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

List of usage examples for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

Introduction

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

Prototype

Thread.UncaughtExceptionHandler

Source Link

Usage

From source file:com.facebook.infrastructure.service.CassandraServer.java

public static void main(String[] args) throws Throwable {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            logger_.error("Fatal exception in thread " + t, e);
        }/*from  w w  w  .j  a  v  a 2s  .  c o  m*/
    });

    try {
        CassandraServer server = new CassandraServer();
        server.start();
        TThreadPoolServer threadPoolServer = thriftEngine(server);
        threadPoolServer.serve();
    } catch (Throwable x) {
        logger_.error("Fatal error; exiting", x);
        System.exit(1);
    }

}

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

From source file:org.apache.storm.utils.Utils.java

/**
 * Creates a thread that calls the given code repeatedly, sleeping for an
 * interval of seconds equal to the return value of the previous call.
 *
 * The given afn may be a callable that returns the number of seconds to
 * sleep, or it may be a Callable that returns another Callable that in turn
 * returns the number of seconds to sleep. In the latter case isFactory.
 *
 * @param afn the code to call on each iteration
 * @param isDaemon whether the new thread should be a daemon thread
 * @param eh code to call when afn throws an exception
 * @param priority the new thread's priority
 * @param isFactory whether afn returns a callable instead of sleep seconds
 * @param startImmediately whether to start the thread before returning
 * @param threadName a suffix to be appended to the thread name
 * @return the newly created thread/*  w  ww.ja  va  2 s.  c om*/
 * @see Thread
 */
public static SmartThread asyncLoop(final Callable afn, boolean isDaemon,
        final Thread.UncaughtExceptionHandler eh, int priority, final boolean isFactory,
        boolean startImmediately, String threadName) {
    SmartThread thread = new SmartThread(new Runnable() {
        public void run() {
            Object s;
            try {
                Callable fn = isFactory ? (Callable) afn.call() : afn;
                while ((s = fn.call()) instanceof Long) {
                    Time.sleepSecs((Long) s);
                }
            } catch (Throwable t) {
                if (exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
                    LOG.info("Async loop interrupted!");
                    return;
                }
                LOG.error("Async loop died!", t);
                throw new RuntimeException(t);
            }
        }
    });
    if (eh != null) {
        thread.setUncaughtExceptionHandler(eh);
    } else {
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                LOG.error("Async loop died!", e);
                exitProcess(1, "Async loop died!");
            }
        });
    }
    thread.setDaemon(isDaemon);
    thread.setPriority(priority);
    if (threadName != null && !threadName.isEmpty()) {
        thread.setName(thread.getName() + "-" + threadName);
    }
    if (startImmediately) {
        thread.start();
    }
    return thread;
}

From source file:co.cask.cdap.security.server.ExternalAuthenticationServer.java

@Override
protected Executor executor(State state) {
    final AtomicInteger id = new AtomicInteger();
    //noinspection NullableProblems
    final Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        @Override//from   www  .j a v  a 2  s. co m
        public void uncaughtException(Thread t, Throwable e) {
        }
    };
    return new Executor() {
        @Override
        public void execute(Runnable runnable) {
            Thread t = new Thread(runnable,
                    String.format("ExternalAuthenticationServer-%d", id.incrementAndGet()));
            t.setUncaughtExceptionHandler(h);
            t.start();
        }
    };
}

From source file:org.pentaho.di.job.entries.hadoopjobexecutor.JobEntryHadoopJobExecutor.java

public Result execute(final Result result, int arg1) throws KettleException {
    result.setNrErrors(0);//from   ww w  .ja v a2s .co m

    Log4jFileAppender appender = null;
    String logFileName = "pdi-" + this.getName(); //$NON-NLS-1$

    try {
        appender = LogWriter.createFileAppender(logFileName, true, false);
        LogWriter.getInstance().addAppender(appender);
        log.setLogLevel(parentJob.getLogLevel());
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.FailedToOpenLogFile", logFileName, //$NON-NLS-1$
                e.toString()));
        logError(Const.getStackTracker(e));
    }

    try {
        URL resolvedJarUrl = resolveJarUrl(jarUrl);
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.ResolvedJar",
                    resolvedJarUrl.toExternalForm()));
        }
        HadoopShim shim = getHadoopConfiguration().getHadoopShim();

        if (isSimple) {
            String simpleLoggingIntervalS = environmentSubstitute(getSimpleLoggingInterval());
            int simpleLogInt = 60;
            try {
                simpleLogInt = Integer.parseInt(simpleLoggingIntervalS, 10);
            } catch (NumberFormatException e) {
                logError(BaseMessages.getString(PKG, "ErrorParsingLogInterval", simpleLoggingIntervalS,
                        simpleLogInt));
            }

            final Class<?> mainClass = locateDriverClass(resolvedJarUrl, shim);

            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.UsingDriverClass",
                        mainClass == null ? "null" : mainClass.getName()));
                logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.SimpleMode"));
            }
            final AtomicInteger threads = new AtomicInteger(1);
            final NoExitSecurityManager nesm = new NoExitSecurityManager(System.getSecurityManager());
            smStack.setSecurityManager(nesm);
            try {
                Runnable r = new Runnable() {
                    public void run() {
                        try {
                            try {
                                executeMainMethod(mainClass);
                            } finally {
                                restoreSecurityManager(threads, nesm);
                            }
                        } catch (NoExitSecurityManager.NoExitSecurityException ex) {
                            // Only log if we're blocking and waiting for this to complete
                            if (simpleBlocking) {
                                logExitStatus(result, mainClass, ex);
                            }
                        } catch (InvocationTargetException ex) {
                            if (ex.getTargetException() instanceof NoExitSecurityManager.NoExitSecurityException) {
                                // Only log if we're blocking and waiting for this to complete
                                if (simpleBlocking) {
                                    logExitStatus(result, mainClass,
                                            (NoExitSecurityManager.NoExitSecurityException) ex
                                                    .getTargetException());
                                }
                            } else {
                                throw new RuntimeException(ex);
                            }
                        } catch (Exception ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                };
                Thread t = new Thread(r);
                t.setDaemon(true);
                t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread t, Throwable e) {
                        restoreSecurityManager(threads, nesm);
                        if (simpleBlocking) {
                            // Only log if we're blocking and waiting for this to complete
                            logError(BaseMessages.getString(JobEntryHadoopJobExecutor.class,
                                    "JobEntryHadoopJobExecutor.ErrorExecutingClass", mainClass.getName()), e);
                            result.setResult(false);
                        }
                    }
                });
                nesm.addBlockedThread(t);
                t.start();
                if (simpleBlocking) {
                    // wait until the thread is done
                    do {
                        logDetailed(BaseMessages.getString(JobEntryHadoopJobExecutor.class,
                                "JobEntryHadoopJobExecutor.Blocking", mainClass.getName()));
                        t.join(simpleLogInt * 1000);
                    } while (!parentJob.isStopped() && t.isAlive());
                    if (t.isAlive()) {
                        // Kill thread if it's still running. The job must have been stopped.
                        t.interrupt();
                    }
                }
            } finally {
                // If we're not performing simple blocking spawn a watchdog thread to restore the security manager when all
                // threads are complete
                if (!simpleBlocking) {
                    Runnable threadWatchdog = new Runnable() {
                        @Override
                        public void run() {
                            while (threads.get() > 0) {
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    /* ignore */
                                }
                            }
                            restoreSecurityManager(threads, nesm);
                        }
                    };
                    Thread watchdog = new Thread(threadWatchdog);
                    watchdog.setDaemon(true);
                    watchdog.start();
                }
            }
        } else {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.AdvancedMode"));
            }
            Configuration conf = shim.createConfiguration();
            FileSystem fs = shim.getFileSystem(conf);
            URL[] urls = new URL[] { resolvedJarUrl };
            URLClassLoader loader = new URLClassLoader(urls, shim.getClass().getClassLoader());
            String hadoopJobNameS = environmentSubstitute(hadoopJobName);
            conf.setJobName(hadoopJobNameS);

            String outputKeyClassS = environmentSubstitute(outputKeyClass);
            conf.setOutputKeyClass(loader.loadClass(outputKeyClassS));
            String outputValueClassS = environmentSubstitute(outputValueClass);
            conf.setOutputValueClass(loader.loadClass(outputValueClassS));

            if (mapperClass != null) {
                String mapperClassS = environmentSubstitute(mapperClass);
                Class<?> mapper = loader.loadClass(mapperClassS);
                conf.setMapperClass(mapper);
            }
            if (combinerClass != null) {
                String combinerClassS = environmentSubstitute(combinerClass);
                Class<?> combiner = loader.loadClass(combinerClassS);
                conf.setCombinerClass(combiner);
            }
            if (reducerClass != null) {
                String reducerClassS = environmentSubstitute(reducerClass);
                Class<?> reducer = loader.loadClass(reducerClassS);
                conf.setReducerClass(reducer);
            }

            if (inputFormatClass != null) {
                String inputFormatClassS = environmentSubstitute(inputFormatClass);
                Class<?> inputFormat = loader.loadClass(inputFormatClassS);
                conf.setInputFormat(inputFormat);
            }
            if (outputFormatClass != null) {
                String outputFormatClassS = environmentSubstitute(outputFormatClass);
                Class<?> outputFormat = loader.loadClass(outputFormatClassS);
                conf.setOutputFormat(outputFormat);
            }

            String hdfsHostnameS = environmentSubstitute(hdfsHostname);
            String hdfsPortS = environmentSubstitute(hdfsPort);
            String jobTrackerHostnameS = environmentSubstitute(jobTrackerHostname);
            String jobTrackerPortS = environmentSubstitute(jobTrackerPort);

            List<String> configMessages = new ArrayList<String>();
            shim.configureConnectionInformation(hdfsHostnameS, hdfsPortS, jobTrackerHostnameS, jobTrackerPortS,
                    conf, configMessages);
            for (String m : configMessages) {
                logBasic(m);
            }

            String inputPathS = environmentSubstitute(inputPath);
            String[] inputPathParts = inputPathS.split(",");
            List<Path> paths = new ArrayList<Path>();
            for (String path : inputPathParts) {
                paths.add(fs.asPath(conf.getDefaultFileSystemURL(), path));
            }
            Path[] finalPaths = paths.toArray(new Path[paths.size()]);

            conf.setInputPaths(finalPaths);
            String outputPathS = environmentSubstitute(outputPath);
            conf.setOutputPath(fs.asPath(conf.getDefaultFileSystemURL(), outputPathS));

            // process user defined values
            for (UserDefinedItem item : userDefined) {
                if (item.getName() != null && !"".equals(item.getName()) && item.getValue() != null
                        && !"".equals(item.getValue())) {
                    String nameS = environmentSubstitute(item.getName());
                    String valueS = environmentSubstitute(item.getValue());
                    conf.set(nameS, valueS);
                }
            }

            conf.setJar(environmentSubstitute(jarUrl));

            String numMapTasksS = environmentSubstitute(numMapTasks);
            String numReduceTasksS = environmentSubstitute(numReduceTasks);
            int numM = 1;
            try {
                numM = Integer.parseInt(numMapTasksS);
            } catch (NumberFormatException e) {
                logError("Can't parse number of map tasks '" + numMapTasksS + "'. Setting num"
                        + "map tasks to 1");
            }
            int numR = 1;
            try {
                numR = Integer.parseInt(numReduceTasksS);
            } catch (NumberFormatException e) {
                logError("Can't parse number of reduce tasks '" + numReduceTasksS + "'. Setting num"
                        + "reduce tasks to 1");
            }

            conf.setNumMapTasks(numM);
            conf.setNumReduceTasks(numR);

            RunningJob runningJob = shim.submitJob(conf);

            String loggingIntervalS = environmentSubstitute(getLoggingInterval());
            int logIntv = 60;
            try {
                logIntv = Integer.parseInt(loggingIntervalS);
            } catch (NumberFormatException e) {
                logError(BaseMessages.getString(PKG, "ErrorParsingLogInterval", loggingIntervalS, logIntv));
            }
            if (blocking) {
                try {
                    int taskCompletionEventIndex = 0;
                    while (!parentJob.isStopped() && !runningJob.isComplete()) {
                        if (logIntv >= 1) {
                            printJobStatus(runningJob);
                            taskCompletionEventIndex = logTaskMessages(runningJob, taskCompletionEventIndex);
                            Thread.sleep(logIntv * 1000);
                        } else {
                            Thread.sleep(60000);
                        }
                    }

                    if (parentJob.isStopped() && !runningJob.isComplete()) {
                        // We must stop the job running on Hadoop
                        runningJob.killJob();
                        // Indicate this job entry did not complete
                        result.setResult(false);
                    }

                    printJobStatus(runningJob);
                    // Log any messages we may have missed while polling
                    logTaskMessages(runningJob, taskCompletionEventIndex);
                } catch (InterruptedException ie) {
                    logError(ie.getMessage(), ie);
                }

                // Entry is successful if the MR job is successful overall
                result.setResult(runningJob.isSuccessful());
            }

        }
    } catch (Throwable t) {
        t.printStackTrace();
        result.setStopped(true);
        result.setNrErrors(1);
        result.setResult(false);
        logError(t.getMessage(), t);
    }

    if (appender != null) {
        LogWriter.getInstance().removeAppender(appender);
        appender.close();

        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, appender.getFile(),
                parentJob.getJobname(), getName());
        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
    }

    return result;
}

From source file:nlp.mediawiki.parser.MultistreamBzip2XmlDumpParser.java

@Override
public void run() {
    final AtomicBoolean terminate = new AtomicBoolean(false);
    final Logger logger = LoggerFactory.getLogger(MultistreamBzip2XmlDumpParser.class);
    //1. Start all worker threads
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new Worker();
        workers[i].setName("Dump Worker " + i);
    }/* w w  w.jav  a  2s  .c  o m*/

    //Add an uncaught exception handler and allow for a graceful shutdown.
    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            logger.error("Fatal error in thread {}, terminating...", th.getName(), ex);
            for (Worker worker : workers) {
                worker.interrupt();
            }
            terminate.set(true);
        }
    };

    for (Worker worker : workers) {
        worker.setUncaughtExceptionHandler(h);
        worker.start();
    }

    //2. Seed them with data until there is no more
    PageBlock data;
    while ((data = pageReader.next()) != null && !terminate.get()) {
        try {
            blocks.put(data);
        } catch (InterruptedException e) {
            logger.error("Data put interrupted", e);
            break;
        }
    }

    for (int i = 0; i < workers.length; i++) {
        try {
            blocks.put(new PageBlock(null, null));
        } catch (InterruptedException e) {
            logger.info("Termination interrupted", e);
            break;
        }
    }

    //3. Await termination of all workers
    for (Worker worker : workers) {
        try {
            worker.join();
        } catch (InterruptedException e) {
            logger.error("Worker {} thread interrupted.", worker.getName(), e);
        }
    }

    output(Collections.<Page>emptyList());
}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

private JSONObject unpackApk() {

    final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override/*from w  w w .  j  a v a  2  s  .  c o m*/
        public void uncaughtException(Thread t, Throwable e) {

            LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString());
            m_progressStream.putStream("Uncaught exception: " + t.getName());
            m_progressStream.putStream("Uncaught exception: " + e.toString());
        }
    };

    m_unpack_apk_time = System.currentTimeMillis(); // Save start time for tracking

    m_unpackApkThread = new Thread(m_threadGroup, new Runnable() {
        @Override
        public void run() {
            boolean success = false;
            try {

                m_progressStream = new ProgressStream(
                        new OmniFile(m_volumeId, m_appFolderPath + "unpack_apk_log.txt"));
                m_progressStream.putStream("Unpack APK starting");
                if (m_apkFile.exists() && m_apkFile.isFile()) {

                    // Extract all files except for XML, to be extracted later
                    success = ApkZipUtil.unzipAllExceptXML(m_apkFile, m_appFolder, m_progressStream);

                    ApkParser apkParser = ApkParser.create(m_apkFile.getStdFile());
                    ArrayList<OmniFile> dexFiles = new ArrayList<>();

                    // Get a list of all files in the APK and iterate and extract by type
                    List<String> paths = OmniZip.getFilesList(m_apkFile);
                    for (String path : paths) {

                        OmniFile file = new OmniFile(m_volumeId, m_appFolderPath + path);
                        OmniUtil.forceMkdirParent(file);

                        String extension = FilenameUtils.getExtension(path);

                        if (extension.contentEquals("xml")) {

                            String xml = apkParser.transBinaryXml(path);
                            OmniUtil.writeFile(file, xml);
                            m_progressStream.putStream("Translated: " + path);
                        }
                        if (extension.contentEquals("dex")) {
                            dexFiles.add(file);
                        }
                    }
                    paths = null; // Release memory

                    // Write over manifest with unencoded version
                    String manifestXml = apkParser.getManifestXml();
                    OmniFile manifestFile = new OmniFile(m_volumeId, m_appFolderPath + "AndroidManifest.xml");
                    OmniUtil.writeFile(manifestFile, manifestXml);
                    m_progressStream.putStream("Translated and parsed: " + "AndroidManifest.xml");

                    // Uses original author CaoQianLi's apk-parser
                    // compile 'net.dongliu:apk-parser:2.1.7'
                    //                        for( CertificateMeta cm : apkParser.getCertificateMetaList()){
                    //
                    //                            m_progressStream.putStream("Certficate base64 MD5: "+cm.getCertBase64Md5());
                    //                            m_progressStream.putStream("Certficate MD5: "+cm.getCertMd5());
                    //                            m_progressStream.putStream("Sign algorithm OID: "+cm.getSignAlgorithmOID());
                    //                            m_progressStream.putStream("Sign algorithm: "+cm.getSignAlgorithm());
                    //                        }

                    for (OmniFile f : dexFiles) {

                        String formatted_count = String.format(Locale.US, "%,d", f.length()) + " bytes";
                        m_progressStream.putStream("DEX extracted: " + f.getName() + ": " + formatted_count);
                    }
                    dexFiles = new ArrayList<>();// Release memory

                    CertificateMeta cm = null;
                    try {
                        cm = apkParser.getCertificateMeta();
                        m_progressStream.putStream("Certficate base64 MD5: " + cm.certBase64Md5);
                        m_progressStream.putStream("Certficate MD5: " + cm.certMd5);
                        m_progressStream.putStream("Sign algorithm OID: " + cm.signAlgorithmOID);
                        m_progressStream.putStream("Sign algorithm: " + cm.signAlgorithm);

                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }

                    m_progressStream.putStream("ApkSignStatus: " + apkParser.verifyApk());

                    /**
                     * Create a file for the user to include classes to omit in the optimize DEX task.
                     */
                    OmniFile optimizedDexOF = new OmniFile(m_volumeId,
                            m_appFolderPath + OPTIMIZED_CLASSES_EXCLUSION_FILENAME);
                    if (!optimizedDexOF.exists()) {

                        String assetFilePath = CConst.ASSET_DATA_FOLDER + OPTIMIZED_CLASSES_EXCLUSION_FILENAME;
                        OmniFile omniFile = new OmniFile(m_volumeId,
                                m_appFolderPath + OPTIMIZED_CLASSES_EXCLUSION_FILENAME);
                        OmniUtil.copyAsset(m_ctx, assetFilePath, omniFile);

                        m_progressStream.putStream("File created: " + OPTIMIZED_CLASSES_EXCLUSION_FILENAME);
                    }
                    /**
                     * Create a README file for the user.
                     */
                    OmniFile README_file = new OmniFile(m_volumeId, m_appFolderPath + README_FILENAME);
                    if (!README_file.exists()) {

                        String assetFilePath = CConst.ASSET_DATA_FOLDER + README_FILENAME;
                        OmniFile omniFile = new OmniFile(m_volumeId, m_appFolderPath + README_FILENAME);
                        OmniUtil.copyAsset(m_ctx, assetFilePath, omniFile);

                        m_progressStream.putStream("File created: " + README_FILENAME);
                    }
                } else {
                    m_progressStream.putStream("APK not found. Select Extract APK.");
                }

            } catch (Exception | StackOverflowError e) {
                m_progressStream.putStream(e.toString());
            }
            String time = TimeUtil.deltaTimeHrMinSec(m_unpack_apk_time);
            m_unpack_apk_time = 0;
            if (success) {
                m_progressStream.putStream("Unpack APK complete: " + time);
            } else {
                m_progressStream.putStream("Unpack APK failed: " + time);
            }
            m_progressStream.close();

        }
    }, UNZIP_APK_THREAD, STACK_SIZE);

    m_unpackApkThread.setPriority(Thread.MAX_PRIORITY);
    m_unpackApkThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    m_unpackApkThread.start();

    final JSONObject wrapper = new JSONObject();
    try {
        wrapper.put("unpack_apk_thread", getThreadStatus(true, m_unpackApkThread));

    } catch (JSONException e) {
        LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
    }

    return wrapper;
}

From source file:org.ut.biolab.medsavant.MedSavantServlet.java

private void setExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*from   ww w  . ja v  a2  s.co m*/
        public void uncaughtException(Thread t, Throwable e) {
            LOG.info("Global exception handler caught: " + t.getName() + ": " + e);

            if (e instanceof InvocationTargetException) {
                e = ((InvocationTargetException) e).getCause();
            }

            if (e instanceof SessionExpiredException) {
                SessionExpiredException see = (SessionExpiredException) e;
                LOG.error("Session expired exception: " + see.toString());
                return;
            }
            e.printStackTrace();
        }
    });
}

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//from  w  w  w .ja  v  a2 s.  c o 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:org.apache.qpid.server.Main.java

protected void setExceptionHandler() {
    Thread.UncaughtExceptionHandler handler = null;
    String handlerClass = System.getProperty("qpid.broker.exceptionHandler");
    if (handlerClass != null) {
        try {//w  ww.  j  a v a2 s.com
            handler = (Thread.UncaughtExceptionHandler) Class.forName(handlerClass).newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | ClassCastException e) {

        }
    }

    if (handler == null) {
        handler = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(final Thread t, final Throwable e) {
                boolean continueOnError = Boolean.getBoolean("qpid.broker.exceptionHandler.continue");
                try {
                    System.err.println(
                            "########################################################################");
                    System.err.println("#");
                    System.err.print("# Unhandled Exception ");
                    System.err.print(e.toString());
                    System.err.print(" in Thread ");
                    System.err.println(t.getName());
                    System.err.println("#");
                    System.err.println(continueOnError
                            ? "# Forced to continue by JVM setting 'qpid.broker.exceptionHandler.continue'"
                            : "# Exiting");
                    System.err.println("#");
                    System.err.println(
                            "########################################################################");
                    e.printStackTrace(System.err);

                    Logger logger = LoggerFactory.getLogger("org.apache.qpid.server.Main");
                    logger.error("Uncaught exception, " + (continueOnError ? "continuing." : "shutting down."),
                            e);
                } finally {
                    if (!continueOnError) {
                        Runtime.getRuntime().halt(1);
                    }
                }

            }
        };

        Thread.setDefaultUncaughtExceptionHandler(handler);
    }
}