Search in sources :

Example 11 with UncaughtExceptionHandler

use of java.lang.Thread.UncaughtExceptionHandler in project robovm by robovm.

the class TimerTest method testThrowingTaskKillsTimerThread.

/**
     * We used to swallow RuntimeExceptions thrown by tasks. Instead, we need to
     * let those exceptions bubble up, where they will both notify the thread's
     * uncaught exception handler and terminate the timer's thread.
     */
public void testThrowingTaskKillsTimerThread() throws Exception {
    final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
    new Timer().schedule(new TimerTask() {

        @Override
        public void run() {
            Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

                public void uncaughtException(Thread thread, Throwable ex) {
                }
            });
            threadRef.set(Thread.currentThread());
            throw new RuntimeException("task failure!");
        }
    }, 1);
    Thread.sleep(400);
    Thread timerThread = threadRef.get();
    assertFalse(timerThread.isAlive());
}
Also used : Timer(java.util.Timer) TimerTask(java.util.TimerTask) AtomicReference(java.util.concurrent.atomic.AtomicReference) UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)

Example 12 with UncaughtExceptionHandler

use of java.lang.Thread.UncaughtExceptionHandler in project platform_frameworks_base by android.

the class UiAutomatorTestRunner method run.

public void run(List<String> testClasses, Bundle params, boolean debug, boolean monkey) {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e(LOGTAG, "uncaught exception", ex);
            Bundle results = new Bundle();
            results.putString("shortMsg", ex.getClass().getName());
            results.putString("longMsg", ex.getMessage());
            mWatcher.instrumentationFinished(null, 0, results);
            // bailing on uncaught exception
            System.exit(EXIT_EXCEPTION);
        }
    });
    mTestClasses = testClasses;
    mParams = params;
    mDebug = debug;
    mMonkey = monkey;
    start();
    System.exit(EXIT_OK);
}
Also used : Bundle(android.os.Bundle) UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) HandlerThread(android.os.HandlerThread)

Example 13 with UncaughtExceptionHandler

use of java.lang.Thread.UncaughtExceptionHandler in project springside4 by springside.

the class ForkJoinPool method registerWorker.

//  Registering and deregistering workers
/**
     * Callback from ForkJoinWorkerThread to establish and record its
     * WorkQueue. To avoid scanning bias due to packing entries in
     * front of the workQueues array, we treat the array as a simple
     * power-of-two hash table using per-thread seed as hash,
     * expanding as needed.
     *
     * @param wt the worker thread
     * @return the worker's queue
     */
final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
    UncaughtExceptionHandler handler;
    WorkQueue[] ws;
    int s, ps;
    wt.setDaemon(true);
    if ((handler = ueh) != null)
        wt.setUncaughtExceptionHandler(handler);
    do {
    } while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed, s += SEED_INCREMENT) || // skip 0
    s == 0);
    WorkQueue w = new WorkQueue(this, wt, mode, s);
    if (((ps = plock) & PL_LOCK) != 0 || !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
        ps = acquirePlock();
    int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
    try {
        if ((ws = workQueues) != null) {
            // skip if shutting down
            int n = ws.length, m = n - 1;
            // use odd-numbered indices
            int r = (s << 1) | 1;
            if (ws[r &= m] != null) {
                // collision
                // step by approx half size
                int probes = 0;
                int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
                while (ws[r = (r + step) & m] != null) {
                    if (++probes >= n) {
                        workQueues = ws = Arrays.copyOf(ws, n <<= 1);
                        m = n - 1;
                        probes = 0;
                    }
                }
            }
            w.poolIndex = (short) r;
            // volatile write orders
            w.eventCount = r;
            ws[r] = w;
        }
    } finally {
        if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
            releasePlock(nps);
    }
    wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex >>> 1)));
    return w;
}
Also used : UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)

Example 14 with UncaughtExceptionHandler

use of java.lang.Thread.UncaughtExceptionHandler in project springside4 by springside.

the class ForkJoinPool method makeCommonPool.

/**
     * Creates and returns the common pool, respecting user settings
     * specified via system properties.
     */
private static ForkJoinPool makeCommonPool() {
    int parallelism = -1;
    ForkJoinWorkerThreadFactory factory = defaultForkJoinWorkerThreadFactory;
    UncaughtExceptionHandler handler = null;
    try {
        // ignore exceptions in accessing/parsing properties
        String pp = System.getProperty("java.util.concurrent.ForkJoinPool.common.parallelism");
        String fp = System.getProperty("java.util.concurrent.ForkJoinPool.common.threadFactory");
        String hp = System.getProperty("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
        if (pp != null)
            parallelism = Integer.parseInt(pp);
        if (fp != null)
            factory = ((ForkJoinWorkerThreadFactory) ClassLoader.getSystemClassLoader().loadClass(fp).newInstance());
        if (hp != null)
            handler = ((UncaughtExceptionHandler) ClassLoader.getSystemClassLoader().loadClass(hp).newInstance());
    } catch (Exception ignore) {
    }
    if (// default 1 less than #cores
    parallelism < 0 && (parallelism = Runtime.getRuntime().availableProcessors() - 1) < 0)
        parallelism = 0;
    if (parallelism > MAX_CAP)
        parallelism = MAX_CAP;
    return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE, "ForkJoinPool.commonPool-worker-");
}
Also used : UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Example 15 with UncaughtExceptionHandler

use of java.lang.Thread.UncaughtExceptionHandler in project torodb by torodb.

the class Main method main.

public static void main(String[] args) throws Exception {
    try {
        Console console = JCommander.getConsole();
        ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
        final CliConfig cliConfig = new CliConfig();
        JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
        jCommander.setColumnSize(Integer.MAX_VALUE);
        if (cliConfig.isVersion()) {
            BuildProperties buildProperties = new DefaultBuildProperties();
            console.println(buildProperties.getFullVersion());
            System.exit(0);
        }
        if (cliConfig.isHelp()) {
            jCommander.usage();
            System.exit(0);
        }
        if (cliConfig.isHelpParam()) {
            console.println(cliBundle.getString("cli.help-param-header"));
            ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, cliBundle, console, 0);
            System.exit(0);
        }
        cliConfig.addParams();
        final Config config = CliConfigUtils.readConfig(cliConfig);
        if (cliConfig.isPrintConfig()) {
            ConfigUtils.printYamlConfig(config, console);
            System.exit(0);
        }
        if (cliConfig.isPrintXmlConfig()) {
            ConfigUtils.printXmlConfig(config, console);
            System.exit(0);
        }
        if (cliConfig.isPrintParam()) {
            JsonNode jsonNode = ConfigUtils.getParam(config, cliConfig.getPrintParamPath());
            if (jsonNode != null) {
                console.print(jsonNode.asText());
            }
            System.exit(0);
        }
        configureLogger(cliConfig, config);
        config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {

            @Override
            public void visit(AbstractDerby value) {
                parseToropassFile(value);
            }

            @Override
            public void visit(AbstractPostgres value) {
                parseToropassFile(value);
            }

            public void parseToropassFile(BackendPasswordConfig value) {
                try {
                    ConfigUtils.parseToropassFile(value);
                } catch (Exception ex) {
                    throw new SystemException(ex);
                }
            }
        });
        AbstractReplication replication = config.getReplication();
        if (replication.getAuth().getUser() != null) {
            HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource()).withDefaultPort(27017);
            ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                @Override
                public void setPassword(String password) {
                    replication.getAuth().setPassword(password);
                }

                @Override
                public String getUser() {
                    return replication.getAuth().getUser();
                }

                @Override
                public Integer getPort() {
                    return syncSource.getPort();
                }

                @Override
                public String getPassword() {
                    return replication.getAuth().getPassword();
                }

                @Override
                public String getMongopassFile() {
                    return config.getReplication().getMongopassFile();
                }

                @Override
                public String getHost() {
                    return syncSource.getHostText();
                }

                @Override
                public String getDatabase() {
                    return replication.getAuth().getSource();
                }
            });
        }
        if (config.getBackend().isLike(AbstractPostgres.class)) {
            AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);
            if (cliConfig.isAskForPassword()) {
                console.print("Type database user " + postgres.getUser() + "'s password:");
                postgres.setPassword(readPwd());
            }
            if (postgres.getPassword() == null) {
                throw new SystemException("No password provided for database user " + postgres.getUser() + ".\n\n" + "Please add following line to file " + postgres.getToropassFile() + ":\n" + postgres.getHost() + ":" + postgres.getPort() + ":" + postgres.getDatabase() + ":" + postgres.getUser() + ":<password>\n" + "Replace <password> for database user " + postgres.getUser() + "'s password");
            }
        }
        try {
            Clock clock = Clock.systemDefaultZone();
            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

                @Override
                @SuppressFBWarnings(value = "DM_EXIT", justification = "Since is really hard to stop cleanly all threads when an OOME is thrown we must " + "exit to avoid no more action is performed that could lead to an unespected " + "state")
                public void uncaughtException(Thread t, Throwable e) {
                    if (e instanceof OutOfMemoryError) {
                        try {
                            LOGGER.error("Fatal out of memory: " + e.getLocalizedMessage(), e);
                        } finally {
                            System.exit(1);
                        }
                    }
                }
            });
            Service stampedeService = StampedeBootstrap.createStampedeService(config, clock);
            stampedeService.startAsync();
            stampedeService.awaitTerminated();
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                stampedeService.stopAsync();
                stampedeService.awaitTerminated();
            }));
        } catch (CreationException ex) {
            ex.getErrorMessages().stream().forEach(m -> {
                if (m.getCause() != null) {
                    LOGGER.error(m.getCause().getMessage());
                } else {
                    LOGGER.error(m.getMessage());
                }
            });
            LogManager.shutdown();
            System.exit(1);
        }
    } catch (Throwable ex) {
        LOGGER.debug("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        LogManager.shutdown();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}
Also used : UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) Config(com.torodb.stampede.config.model.Config) AbstractPostgres(com.torodb.packaging.config.model.backend.postgres.AbstractPostgres) BackendImplementationVisitor(com.torodb.packaging.config.visitor.BackendImplementationVisitor) DefaultBuildProperties(com.torodb.packaging.DefaultBuildProperties) ConfigUtils(com.torodb.packaging.config.util.ConfigUtils) ResourceBundle(java.util.ResourceBundle) AbstractReplication(com.torodb.packaging.config.model.protocol.mongo.AbstractReplication) JsonNode(com.fasterxml.jackson.databind.JsonNode) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) Charsets(com.google.common.base.Charsets) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig) JCommander(com.beust.jcommander.JCommander) Throwables(com.google.common.base.Throwables) PropertyResourceBundle(java.util.PropertyResourceBundle) IOException(java.io.IOException) Console(com.beust.jcommander.internal.Console) HostAndPort(com.google.common.net.HostAndPort) Service(com.google.common.util.concurrent.Service) SystemException(com.torodb.core.exceptions.SystemException) CreationException(com.google.inject.CreationException) Logger(org.apache.logging.log4j.Logger) BuildProperties(com.torodb.core.BuildProperties) AbstractDerby(com.torodb.packaging.config.model.backend.derby.AbstractDerby) Clock(java.time.Clock) Log4jUtils(com.torodb.packaging.util.Log4jUtils) LogManager(org.apache.logging.log4j.LogManager) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) InputStream(java.io.InputStream) Config(com.torodb.stampede.config.model.Config) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig) BackendImplementationVisitor(com.torodb.packaging.config.visitor.BackendImplementationVisitor) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) DefaultBuildProperties(com.torodb.packaging.DefaultBuildProperties) JsonNode(com.fasterxml.jackson.databind.JsonNode) Clock(java.time.Clock) HostAndPort(com.google.common.net.HostAndPort) SystemException(com.torodb.core.exceptions.SystemException) JCommander(com.beust.jcommander.JCommander) Console(com.beust.jcommander.internal.Console) UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) Service(com.google.common.util.concurrent.Service) CreationException(com.google.inject.CreationException) AbstractReplication(com.torodb.packaging.config.model.protocol.mongo.AbstractReplication) AbstractPostgres(com.torodb.packaging.config.model.backend.postgres.AbstractPostgres) IOException(java.io.IOException) SystemException(com.torodb.core.exceptions.SystemException) CreationException(com.google.inject.CreationException) DefaultBuildProperties(com.torodb.packaging.DefaultBuildProperties) BuildProperties(com.torodb.core.BuildProperties) ResourceBundle(java.util.ResourceBundle) PropertyResourceBundle(java.util.PropertyResourceBundle) AbstractDerby(com.torodb.packaging.config.model.backend.derby.AbstractDerby) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig)

Aggregations

UncaughtExceptionHandler (java.lang.Thread.UncaughtExceptionHandler)51 Bundle (android.os.Bundle)5 HandlerThread (android.os.HandlerThread)5 IOException (java.io.IOException)5 AtomicLong (java.util.concurrent.atomic.AtomicLong)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 CountDownLatch (java.util.concurrent.CountDownLatch)4 ThreadFactory (java.util.concurrent.ThreadFactory)4 Test (org.junit.Test)4 LocalLoadingCache (com.google.common.cache.LocalCache.LocalLoadingCache)2 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)2 Intent (android.content.Intent)1 Message (android.os.Message)1 PowerManager (android.os.PowerManager)1 RemoteException (android.os.RemoteException)1 ConsoleMessage (android.webkit.ConsoleMessage)1 SmartThread (com.alibaba.jstorm.utils.SmartThread)1 JCommander (com.beust.jcommander.JCommander)1 Console (com.beust.jcommander.internal.Console)1 LowLevelHeartBeatEvent (com.carrotsearch.ant.tasks.junit4.events.LowLevelHeartBeatEvent)1