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:org.apache.hadoop.net.unix.TestDomainSocketWatcher.java

/**
 * Creates a new DomainSocketWatcher and tracks its thread for termination due
 * to an unexpected exception.  At the end of each test, if there was an
 * unexpected exception, then that exception is thrown to force a failure of
 * the test./*from  w  w w .j  a  v  a 2s  .  c  o  m*/
 *
 * @param interruptCheckPeriodMs interrupt check period passed to
 *     DomainSocketWatcher
 * @return new DomainSocketWatcher
 * @throws Exception if there is any failure
 */
private DomainSocketWatcher newDomainSocketWatcher(int interruptCheckPeriodMs) throws Exception {
    DomainSocketWatcher watcher = new DomainSocketWatcher(interruptCheckPeriodMs, getClass().getSimpleName());
    watcher.watcherThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable t) {
            trappedException = t;
        }
    });
    return watcher;
}

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/*from   w w  w  .  j a va2 s. com*/
        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:com.inmobi.conduit.AbstractService.java

@Override
public synchronized void start() {
    thread = new Thread(this, this.name);
    LOG.info("Starting thread " + thread.getName());
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        public void uncaughtException(Thread t, Throwable e) {
            LOG.error("Thread: " + thread + " Uncaught handler:" + " Thread interrupt status: "
                    + thread.isInterrupted() + " and exception caught is: " + e);
        }//from   w w w.  java  2  s  .  c  om
    });
    thread.start();
}

From source file:lcmc.LCMC.java

/** Inits the application. */
protected static String initApp(final String[] args) {
    try {//from  w  ww  .j a  va 2  s  . co  m
        /* Metal */
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        MetalLookAndFeel.setCurrentTheme(new OceanTheme() {
            /** e.g. arrows on split pane... */
            protected ColorUIResource getPrimary1() {
                return new ColorUIResource(ClusterBrowser.STATUS_BACKGROUND);
            }

            /** unknown to me */
            protected ColorUIResource getPrimary2() {
                return new ColorUIResource(ClusterBrowser.PANEL_BACKGROUND);
            }

            /** unknown to me */
            protected ColorUIResource getPrimary3() {
                return new ColorUIResource(ClusterBrowser.PANEL_BACKGROUND);
            }

            /** Button and other borders. */
            protected ColorUIResource getSecondary1() {
                return new ColorUIResource(AppDefaults.BACKGROUND_DARK);
            }

            protected ColorUIResource getSecondary2() {
                return new ColorUIResource(ClusterBrowser.PANEL_BACKGROUND);
            }

            /** Split pane divider. Line in the main menu. */
            protected ColorUIResource getSecondary3() {
                return new ColorUIResource(ClusterBrowser.PANEL_BACKGROUND);
            }
        });
    } catch (final Exception e) {
        /* ignore it then */
    }
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(final Thread t, final Throwable ex) {
            Tools.appError("uncaught exception", ex.toString(), (Exception) ex);
        }
    });
    float fps = 20.0f;
    final Options options = new Options();

    options.addOption("h", HELP_OP, false, "print this help");
    options.addOption(null, KEEP_HELPER_OP, false, "do not overwrite the lcmc-gui-helper program");
    options.addOption(null, RO_OP, false, "read only mode");
    options.addOption(null, OP_OP, false, "operator mode");
    options.addOption(null, ADMIN_OP, false, "administrator mode");
    options.addOption(null, OP_MODE_OP, true, "operating mode. <arg> can be:\n" + "ro - read only\n"
            + "op - operator\n" + "admin - administrator");
    options.addOption(null, NOLRM_OP, false, "do not show removed resources from LRM.");
    options.addOption(null, "auto", true, "for testing");
    options.addOption("v", VERSION_OP, false, "print version");
    options.addOption(null, AUTO_OP, true, "for testing");
    options.addOption(null, NO_UPGRADE_CHECK_OP, false, "disable upgrade check");
    options.addOption(null, NO_PLUGIN_CHECK_OP, false,
            "disable plugin check, DEPRECATED: there are no plugins");
    options.addOption(null, TIGHTVNC_OP, false, "enable tight vnc viewer");
    options.addOption(null, ULTRAVNC_OP, false, "enable ultra vnc viewer");
    options.addOption(null, REALVNC_OP, false, "enable real vnc viewer");
    options.addOption(null, BIGDRBDCONF_OP, false,
            "create one big drbd.conf, instead of many" + " files in drbd.d/ directory");
    options.addOption(null, STAGING_DRBD_OP, false, "enable more DRBD installation options");
    options.addOption(null, STAGING_PACEMAKER_OP, false, "enable more Pacemaker installation options");
    options.addOption(null, VNC_PORT_OFFSET_OP, true, "offset for port forwarding");
    options.addOption(null, SLOW_OP, false, "specify this if you have slow computer");
    options.addOption(null, RESTORE_MOUSE_OP, false, "for testing");
    options.addOption(null, SCALE_OP, true, "scale fonts and sizes of elements in percent (100)");
    options.addOption(null, ID_DSA_OP, true, "location of id_dsa file ($HOME/.ssh/id_dsa)");
    options.addOption(null, ID_RSA_OP, true, "location of id_rsa file ($HOME/.ssh/id_rsa)");
    options.addOption(null, KNOWN_HOSTS_OP, true, "location of known_hosts file ($HOME/.ssh/known_hosts)");
    options.addOption(null, OUT_OP, true, "where to redirect the standard out");
    options.addOption(null, DEBUG_OP, true, "debug level, 0 - none, 3 - all");
    options.addOption("c", CLUSTER_OP, true, "define a cluster");
    final Option hostOp = new Option("h", HOST_OP, true, "define a cluster, used with --cluster option");
    hostOp.setArgs(10000);
    options.addOption(hostOp);
    options.addOption(null, SUDO_OP, false, "whether to use sudo, used with --cluster option");
    options.addOption(null, USER_OP, true, "user to use with sudo, used with --cluster option");
    options.addOption(null, PORT_OP, true, "ssh port, used with --cluster option");
    options.addOption(null, ADVANCED_OP, false, "start in an advanced mode");
    options.addOption(null, ONE_HOST_CLUSTER_OP, false, "allow one host cluster");
    final CommandLineParser parser = new PosixParser();
    String autoArgs = null;
    try {
        final CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption(OUT_OP)) {
            final String out = cmd.getOptionValue(OUT_OP);
            if (out != null) {
                try {
                    System.setOut(new PrintStream(new FileOutputStream(out)));
                } catch (final FileNotFoundException e) {
                    System.exit(2);
                }
            }
        }
        if (cmd.hasOption(DEBUG_OP)) {
            final String level = cmd.getOptionValue(DEBUG_OP);
            if (level != null && Tools.isNumber(level)) {
                Tools.setDebugLevel(Integer.parseInt(level));
            } else {
                throw new ParseException("cannot parse debug level: " + level);
            }
        }
        boolean tightvnc = cmd.hasOption(TIGHTVNC_OP);
        boolean ultravnc = cmd.hasOption(ULTRAVNC_OP);
        final boolean realvnc = cmd.hasOption(REALVNC_OP);
        if (!tightvnc && !ultravnc && !realvnc) {
            if (Tools.isLinux()) {
                tightvnc = true;
            } else if (Tools.isWindows()) {
                ultravnc = true;
            } else {
                tightvnc = true;
                ultravnc = true;
            }
        }
        boolean advanced = cmd.hasOption(ADVANCED_OP);
        Tools.getConfigData().setAdvancedMode(advanced);
        Tools.getConfigData().setTightvnc(tightvnc);
        Tools.getConfigData().setUltravnc(ultravnc);
        Tools.getConfigData().setRealvnc(realvnc);

        Tools.getConfigData().setUpgradeCheckEnabled(!cmd.hasOption(NO_UPGRADE_CHECK_OP));
        Tools.getConfigData().setBigDRBDConf(cmd.hasOption(BIGDRBDCONF_OP));
        Tools.getConfigData().setStagingDrbd(cmd.hasOption(STAGING_DRBD_OP));
        Tools.getConfigData().setStagingPacemaker(cmd.hasOption(STAGING_PACEMAKER_OP));
        Tools.getConfigData().setNoLRM(cmd.hasOption(NOLRM_OP));
        Tools.getConfigData().setKeepHelper(cmd.hasOption(KEEP_HELPER_OP));
        Tools.getConfigData().setOneHostCluster(cmd.hasOption(ONE_HOST_CLUSTER_OP));
        final String pwd = System.getProperty("user.home");
        final String scaleOp = cmd.getOptionValue(SCALE_OP, "100");
        try {
            final int scale = Integer.parseInt(scaleOp);
            Tools.getConfigData().setScale(scale);
            Tools.resizeFonts(scale);
        } catch (java.lang.NumberFormatException e) {
            Tools.appWarning("cannot parse scale: " + scaleOp);
        }

        final String idDsaPath = cmd.getOptionValue(ID_DSA_OP, pwd + "/.ssh/id_dsa");
        final String idRsaPath = cmd.getOptionValue(ID_RSA_OP, pwd + "/.ssh/id_rsa");
        final String knownHostsPath = cmd.getOptionValue(KNOWN_HOSTS_OP, pwd + "/.ssh/known_hosts");
        Tools.getConfigData().setIdDSAPath(idDsaPath);
        Tools.getConfigData().setIdRSAPath(idRsaPath);
        Tools.getConfigData().setKnownHostPath(knownHostsPath);

        final String opMode = cmd.getOptionValue(OP_MODE_OP);
        autoArgs = cmd.getOptionValue(AUTO_OP);
        if (cmd.hasOption(HELP_OP)) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar LCMC.jar [OPTIONS]", options);
            System.exit(0);
        }
        if (cmd.hasOption(VERSION_OP)) {
            System.out.println("LINUX CLUSTER MANAGEMENT CONSOLE " + Tools.getRelease() + " by Rasto Levrinc");
            System.exit(0);
        }
        if (cmd.hasOption("ro") || "ro".equals(opMode)) {
            Tools.getConfigData().setAccessType(ConfigData.AccessType.RO);
            Tools.getConfigData().setMaxAccessType(ConfigData.AccessType.RO);
        } else if (cmd.hasOption("op") || "op".equals(opMode)) {
            Tools.getConfigData().setAccessType(ConfigData.AccessType.OP);
            Tools.getConfigData().setMaxAccessType(ConfigData.AccessType.OP);
        } else if (cmd.hasOption("admin") || "admin".equals(opMode)) {
            Tools.getConfigData().setAccessType(ConfigData.AccessType.ADMIN);
            Tools.getConfigData().setMaxAccessType(ConfigData.AccessType.ADMIN);
        } else if (opMode != null) {
            Tools.appWarning("unknown operating mode: " + opMode);
        }
        if (cmd.hasOption(SLOW_OP)) {
            fps = fps / 2;
        }
        if (cmd.hasOption(RESTORE_MOUSE_OP)) {
            /* restore mouse if it is stuck in pressed state, during
             * robot tests. */
            RoboTest.restoreMouse();
        }
        final String vncPortOffsetString = cmd.getOptionValue(VNC_PORT_OFFSET_OP);
        if (vncPortOffsetString != null && Tools.isNumber(vncPortOffsetString)) {
            Tools.getConfigData().setVncPortOffset(Integer.parseInt(vncPortOffsetString));
        }
        Tools.getConfigData().setAnimFPS(fps);
        if (cmd.hasOption(CLUSTER_OP) || cmd.hasOption(HOST_OP)) {
            parseClusterOptions(cmd);
        }
    } catch (ParseException exp) {
        System.out.println("ERROR: " + exp.getMessage());
        System.exit(1);
    }
    Tools.debug(null, "max mem: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m", 1);
    return autoArgs;
}

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;//from w  w w.  j a  v  a  2  s.  co  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.apache.hadoop.hbase.security.AbstractTestSecureIPC.java

/**
 * Sets up a RPC Server and a Client. Does a RPC checks the result. If an exception is thrown
 * from the stub, this function will throw root cause of that exception.
 *///ww  w.j av a 2s  .co m
private void callRpcService(User clientUser) throws Exception {
    SecurityInfo securityInfoMock = Mockito.mock(SecurityInfo.class);
    Mockito.when(securityInfoMock.getServerPrincipal()).thenReturn(HBaseKerberosUtils.KRB_PRINCIPAL);
    SecurityInfo.addInfo("TestProtobufRpcProto", securityInfoMock);

    InetSocketAddress isa = new InetSocketAddress(HOST, 0);

    RpcServerInterface rpcServer = new RpcServer(null, "AbstractTestSecureIPC",
            Lists.newArrayList(new RpcServer.BlockingServiceAndInterface(SERVICE, null)), isa, serverConf,
            new FifoRpcScheduler(serverConf, 1));
    rpcServer.start();
    try (RpcClient rpcClient = RpcClientFactory.createClient(clientConf,
            HConstants.DEFAULT_CLUSTER_ID.toString())) {
        InetSocketAddress address = rpcServer.getListenerAddress();
        if (address == null) {
            throw new IOException("Listener channel is closed");
        }
        BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                clientUser, 0);
        TestRpcServiceProtos.TestProtobufRpcProto.BlockingInterface stub = TestRpcServiceProtos.TestProtobufRpcProto
                .newBlockingStub(channel);
        List<String> results = new ArrayList<>();
        TestThread th1 = new TestThread(stub, results);
        final Throwable exception[] = new Throwable[1];
        Collections.synchronizedList(new ArrayList<Throwable>());
        Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread th, Throwable ex) {
                exception[0] = ex;
            }
        };
        th1.setUncaughtExceptionHandler(exceptionHandler);
        th1.start();
        th1.join();
        if (exception[0] != null) {
            // throw root cause.
            while (exception[0].getCause() != null) {
                exception[0] = exception[0].getCause();
            }
            throw (Exception) exception[0];
        }
    } finally {
        rpcServer.stop();
    }
}

From source file:com.cloudmine.api.db.RequestPerformerService.java

/**
 * This intercepts any uncaught exceptions and restarts the service
 *//* ww w. ja va  2s  .c  om*/
private void catchUncaughtExceptions() {
    final Context applicationContext = getApplicationContext();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {

            LOG.error("Crashed, restarting service ", throwable);
            applicationContext.startService(new Intent(applicationContext, RequestPerformerService.class));

            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }
    });
}

From source file:org.apache.rya.accumulo.mr.merge.MergeTool.java

public static void main(final String[] args) {
    final String log4jConfiguration = System.getProperties().getProperty("log4j.configuration");
    if (StringUtils.isNotBlank(log4jConfiguration)) {
        final String parsedConfiguration = StringUtils.removeStart(log4jConfiguration, "file:");
        final File configFile = new File(parsedConfiguration);
        if (configFile.exists()) {
            DOMConfigurator.configure(parsedConfiguration);
        } else {// w  w w.j a v a2s  .c  o  m
            BasicConfigurator.configure();
        }
    }
    log.info("Starting Merge Tool");

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            log.error("Uncaught exception in " + thread.getName(), throwable);
        }
    });

    final int returnCode = setupAndRun(args);

    log.info("Finished running Merge Tool");

    System.exit(returnCode);
}

From source file:se.lth.cs.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);
    }/*from  w w  w  .ja v a  2  s.  com*/

    //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
    byte[] data;
    while ((data = pageReader.next()) != null && !terminate.get()) {
        try {
            blocks.put(new PageBlock(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));
        } 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: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;/*from  w  ww  . j  a v a 2s  .  co  m*/
                }
            }

            e.printStackTrace();
        }
    });

    t.start();
    return t;
}