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.thoughtworks.go.server.service.PipelineConfigServicePerformanceTest.java

private void run(Runnable runnable, int numberOfRequests, final ConcurrentHashMap<String, Boolean> results)
        throws InterruptedException {
    Boolean finalResult = true;/*from www  .ja v  a  2 s  . co  m*/
    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));
}

From source file:com.linkedin.harisekhon.CLI.java

public final void main2(String[] args) {
    log.trace("running CLI.main2()");
    setup();//from  w ww .j  a  v  a2s .  c om
    try {
        addOptions();
    } catch (IllegalArgumentException e) {
        usage(e);
    }
    try {
        parseArgs2(args);
        //            autoflush();
        // TODO: this will reduce TRACE level, check to only increase log level and never reduce it
        //            if(verbose > 2) {
        //                log.setLevel(Level.DEBUG);
        //            } else if(verbose > 1){
        //                log.setLevel(Level.INFO);
        //            }
        //            if(debug){
        //                log.setLevel(Level.DEBUG);
        //            }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        usage(e.getMessage());
    }
    log.info(String.format("verbose level: %s", verbose));
    validateInt(timeout, "timeout", 0, timeout_max);
    log.info(String.format("setting timeout to %s secs", timeout));
    Thread t = new Thread(new Timeout(timeout));
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof QuitException) {
                println(((QuitException) e).status + ": " + ((QuitException) e).message);
                System.exit(getStatusCode("UNKNOWN"));
            } else {
                // normal Thread.stop() at end of program raises exception with null
                if (e.getMessage() != null) {
                    println(e.getMessage());
                    System.exit(getStatusCode("UNKNOWN"));
                }
            }
        }
    });
    t.start();
    try {
        log.trace("running CLI.processArgs()");
        processArgs();
        log.trace("running CLI.run()");
        run();
        log.trace("running CLI.end()");
        end();
        log.trace("stopping timeout thread");
        t.stop();
    } catch (IllegalArgumentException e) {
        log.trace("caught exception in CLI.main2()");
        if (log.isDebugEnabled()) {
            e.printStackTrace();
            // not as nicely formatted - not printing anything right now??
            //                println(e.getStackTrace().toString());
        }
        usage(e.getMessage());
        // not thrown by try block, how is Control-C thrown?
        //        } catch (InterruptedException e){
        //            System.out.println("Caught control-c...");
        //            System.exit(getStatusCode("UNKNOWN"));
    }
}

From source file:com.datatorrent.lib.appdata.query.SimpleDoneQueryQueueManagerTest.java

private Thread testBlockingNoStop(SimpleDoneQueueManager<Query, Void> sdqqm,
        ExceptionSaverExceptionHandler eseh) throws InterruptedException {
    Thread thread = new Thread(new BlockedThread<>(sdqqm));
    thread.setUncaughtExceptionHandler(eseh);
    thread.start();// w  w  w.  j a v  a 2  s.  co m
    Thread.sleep(100);

    Assert.assertEquals(Thread.State.WAITING, thread.getState());

    return thread;
}

From source file:org.eclipse.gyrex.cloud.services.zookeeper.ZooKeeperBasedService.java

/**
 * Creates a new instance.//from   w  w w  .  java  2  s  .  c om
 * <p>
 * Note, this will not activate the service. Sub-classes must activate the
 * service by calling {@link #activate()} when appropriate. This can happen
 * from within the constructor (after calling this constructor using
 * <code>super(...)</code>) or lazily when active connection traction
 * becomes necessary.
 * </p>
 * 
 * @param retryDelayInMs
 *            the retry delay in milliseconds (must be greater than or equal
 *            to 50)
 * @param retryCount
 *            the number of retries to perform
 */
public ZooKeeperBasedService(final long retryDelayInMs, final int retryCount) {
    if (retryDelayInMs < 50)
        throw new IllegalArgumentException("retry delay to low");
    if (retryCount < 1)
        throw new IllegalArgumentException("retry count to low");
    this.retryDelayInMs = retryDelayInMs;
    this.retryCount = retryCount;
    executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(final Runnable r) {
            final Thread t = new Thread(r, String.format("%s Deferred Executor", ZooKeeperBasedService.this));
            t.setDaemon(true);
            t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(final Thread t, final Throwable e) {
                    LOG.error("Unhandled error processing operation in ({}). {}", ZooKeeperBasedService.this,
                            ExceptionUtils.getRootCauseMessage(e), e);
                }
            });
            return t;
        }
    });
}

From source file:org.opf_labs.utils.ProcessRunnerImpl.java

@SuppressWarnings("resource")
private static void feedProcess(final Process process, final InputStream input) {
    if (input == null) {
        // No complaints here - null just means no input
        return;// w  ww  .ja va2s  . c  o m
    }

    final OutputStream pIn = process.getOutputStream();
    final InputStream given = input;
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                OutputStream writer = null;
                try {
                    writer = new BufferedOutputStream(pIn);
                    int c;
                    while ((c = given.read()) != -1) {
                        writer.write(c);
                    }
                } finally {
                    if (writer != null) {
                        writer.close();
                    }
                    pIn.close();
                }
            } catch (IOException e) {
                // This seems ugly
                throw new RuntimeException("Couldn't write input to " + "process.", e);
            }
        }
    };

    Thread.UncaughtExceptionHandler u = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable e) {
            // Might not be the prettiest solution...
        }
    };
    t.setUncaughtExceptionHandler(u);
    t.start();
    try {
        pIn.close();
    } catch (IOException excep) {
        // Nothing to do
    }
}

From source file:org.killbill.notificationq.NotificationQueueDispatcher.java

NotificationQueueDispatcher(final Clock clock, final NotificationQueueConfig config, final IDBI dbi,
        final MetricRegistry metricRegistry) {
    super("NotificationQ", Executors.newFixedThreadPool(config.getNbThreads() + 1, new ThreadFactory() {
        @Override/*from  w  w  w.  j av  a2s.  c  om*/
        public Thread newThread(final Runnable r) {
            final Thread th = new Thread(r);
            th.setName(config.getTableName() + "-th");
            th.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(final Thread t, final Throwable e) {
                    log.error("Uncaught exception for thread " + t.getName(), e);
                }
            });
            return th;
        }
    }), 1, config);

    this.clock = clock;
    this.config = config;
    this.nbProcessedEvents = new AtomicLong();
    final NotificationSqlDao sqlDao = dbi.onDemand(NotificationSqlDao.class);
    this.dao = new DBBackedQueue<NotificationEventModelDao>(clock, sqlDao, config,
            "notif-" + config.getTableName(), metricRegistry, null);

    this.queues = new TreeMap<String, NotificationQueue>();

    this.processedNotificationsSinceStart = metricRegistry.counter(
            MetricRegistry.name(NotificationQueueDispatcher.class, "processed-notifications-since-start"));
    this.perQueueProcessingTime = new HashMap<String, Histogram>();
    this.pendingNotificationsQ = new LinkedBlockingQueue<NotificationEventModelDao>(config.getQueueCapacity());

    this.metricRegistry = metricRegistry;
    this.pendingNotifications = metricRegistry.register(
            MetricRegistry.name(NotificationQueueDispatcher.class, "pending-notifications"),
            new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return pendingNotificationsQ.size();
                }
            });

    this.runners = new NotificationRunner[config.getNbThreads()];
    for (int i = 0; i < config.getNbThreads(); i++) {
        runners[i] = new NotificationRunner(pendingNotificationsQ, clock, config, objectMapper,
                nbProcessedEvents, queues, dao, perQueueProcessingTime, metricRegistry,
                processedNotificationsSinceStart);
    }
}

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

@Test
public void testRunIngestTimeout() throws Exception {

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

    Thread.UncaughtExceptionHandler jobFailedHandler = new Thread.UncaughtExceptionHandler() {
        @Override// ww  w  . j a  v  a 2  s . co m
        public void uncaughtException(Thread th, Throwable ex) {
            fail("Uncaught exception, job should have completed.");
        }
    };

    Thread jobThread = new Thread(job);
    Thread finishThread = new Thread(jmsListener);

    jobThread.setUncaughtExceptionHandler(jobFailedHandler);

    jobThread.start();
    finishThread.start();

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

    // All ingests, including the timed out object, should have registered as a click
    verify(jobStatusFactory, times(job.getIngestObjectCount() + 1)).incrCompletion(eq(job.getJobUUID()), eq(1));

    // All objects should have been ingested despite the timeout
    verify(client, times(job.getIngestObjectCount() + 1)).ingestRaw(any(byte[].class), any(Format.class),
            anyString());

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

}

From source file:org.knime.knip.ilastik.nodes.headless.IlastikHeadlessNodeModel.java

/**
 * Write stream to knime console/*from  w ww . java  2  s .c  om*/
 *
 * @param in input stream
 * @param logService
 * @throws IOException
 */
static void redirectToKnimeConsole(final InputStream in, final DirectedLogService defaultLogger) {

    Thread t = new Thread() {
        @Override
        public void run() {

            String line;

            try (BufferedReader bis = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset()))) {
                while ((line = bis.readLine()) != null) {
                    if (line.contains("WARNING")) {
                        KNIPGateway.log().warn(line);
                    } else {
                        defaultLogger.log(line);
                    }
                }
            } catch (IOException ioe) {
                throw new RuntimeException("Could not read ilastik output", ioe);
            }
        }
    };

    t.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(KNIPGateway.log()));
    t.start();
}

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 w  w  w.  ja  v  a 2s . c o  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:com.apptentive.android.sdk.Apptentive.java

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