Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

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

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:com.chinamobile.bcbsp.workermanager.WorkerManager.java

/**
 * Start the WorkerManager//from w w w  .j a v a 2s .  com
 *
 * @param hrs WorkerManager
 * @param name the name of thread
 * @return the thread of startWorkerManager
 */
public static Thread startWorkerManager(final WorkerManager hrs, final String name) {
    Thread t = new Thread(hrs);
    t.setName(name);
    t.start();
    return t;
}

From source file:eu.apenet.dpt.standalone.gui.batch.ConvertAndValidateActionListener.java

public void actionPerformed(ActionEvent event) {
    labels = dataPreparationToolGUI.getLabels();
    continueLoop = true;/*from  w w  w  . j av  a  2 s .  co  m*/
    dataPreparationToolGUI.disableAllBtnAndItems();
    dataPreparationToolGUI.disableEditionTab();
    dataPreparationToolGUI.disableRadioButtons();
    dataPreparationToolGUI.disableAllBatchBtns();
    dataPreparationToolGUI.getAPEPanel().setFilename("");
    final Object[] objects = dataPreparationToolGUI.getXmlEadList().getSelectedValues();
    final ApexActionListener apexActionListener = this;
    new Thread(new Runnable() {
        public void run() {
            FileInstance uniqueFileInstance = null;
            String uniqueXslMessage = "";
            int numberOfFiles = objects.length;
            int currentFileNumberBatch = 0;
            ProgressFrame progressFrame = new ProgressFrame(labels, parent, true, false, apexActionListener);
            JProgressBar batchProgressBar = progressFrame.getProgressBarBatch();

            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConversionBtn();
            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableValidationBtn();
            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConvertAndValidateBtn();
            dataPreparationToolGUI.getXmlEadList().setEnabled(false);

            for (Object oneFile : objects) {
                if (!continueLoop) {
                    break;
                }

                File file = (File) oneFile;
                FileInstance fileInstance = dataPreparationToolGUI.getFileInstances().get(file.getName());
                if (numberOfFiles == 1) {
                    uniqueFileInstance = fileInstance;
                }

                if (!fileInstance.isXml()) {
                    fileInstance.setXml(XmlChecker.isXmlParseable(file) == null);
                    if (!fileInstance.isXml()) {
                        if (type == CONVERT || type == CONVERT_AND_VALIDATE) {
                            fileInstance.setConversionErrors(labels.getString("conversion.error.fileNotXml"));
                        } else if (type == VALIDATE || type == CONVERT_AND_VALIDATE) {
                            fileInstance.setValidationErrors(labels.getString("validation.error.fileNotXml"));
                        }
                        dataPreparationToolGUI.enableSaveBtn();
                        dataPreparationToolGUI.enableRadioButtons();
                        dataPreparationToolGUI.enableEditionTab();
                    }
                }

                SummaryWorking summaryWorking = new SummaryWorking(dataPreparationToolGUI.getResultArea(),
                        batchProgressBar);
                summaryWorking.setTotalNumberFiles(numberOfFiles);
                summaryWorking.setCurrentFileNumberBatch(currentFileNumberBatch);
                Thread threadRunner = new Thread(summaryWorking);
                threadRunner.setName(SummaryWorking.class.toString());
                threadRunner.start();

                JProgressBar progressBar = null;

                Thread threadProgress = null;
                CounterThread counterThread = null;
                CounterCLevelCall counterCLevelCall = null;

                if (fileInstance.isXml()) {
                    currentFileNumberBatch = currentFileNumberBatch + 1;
                    if (type == CONVERT || type == CONVERT_AND_VALIDATE) {

                        dataPreparationToolGUI.setResultAreaText(labels.getString("converting") + " "
                                + file.getName() + " (" + (currentFileNumberBatch) + "/" + numberOfFiles + ")");

                        String eadid = "";
                        boolean doTransformation = true;
                        if (fileInstance.getValidationSchema()
                                .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))
                                || fileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))) {
                            StaxTransformationTool staxTransformationTool = new StaxTransformationTool(file);
                            staxTransformationTool.run();
                            LOG.debug("file has eadid? " + staxTransformationTool.isFileWithEadid());
                            if (!staxTransformationTool.isFileWithEadid()) {
                                EadidQueryComponent eadidQueryComponent;
                                if (staxTransformationTool.getUnitid() != null
                                        && !staxTransformationTool.getUnitid().equals("")) {
                                    eadidQueryComponent = new EadidQueryComponent(
                                            staxTransformationTool.getUnitid());
                                } else {
                                    eadidQueryComponent = new EadidQueryComponent(labels);
                                }
                                int result = JOptionPane.showConfirmDialog(parent,
                                        eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"),
                                        JOptionPane.OK_CANCEL_OPTION);
                                while (StringUtils.isEmpty(eadidQueryComponent.getEntryEadid())
                                        && result != JOptionPane.CANCEL_OPTION) {
                                    result = JOptionPane.showConfirmDialog(parent,
                                            eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"),
                                            JOptionPane.OK_CANCEL_OPTION);
                                }
                                if (result == JOptionPane.OK_OPTION) {
                                    eadid = eadidQueryComponent.getEntryEadid();
                                } else if (result == JOptionPane.CANCEL_OPTION) {
                                    doTransformation = false;
                                }
                            }
                        }
                        if (doTransformation) {
                            int counterMax = 0;
                            if (fileInstance.getConversionScriptName()
                                    .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) {
                                progressBar = progressFrame.getProgressBarSingle();
                                progressBar.setVisible(true);
                                progressFrame
                                        .setTitle(labels.getString("progressTrans") + " - " + file.getName());
                                CountCLevels countCLevels = new CountCLevels();
                                counterMax = countCLevels.countOneFile(file);
                                if (counterMax > 0) {
                                    counterCLevelCall = new CounterCLevelCall();
                                    counterCLevelCall.initializeCounter(counterMax);
                                    counterThread = new CounterThread(counterCLevelCall, progressBar,
                                            counterMax);
                                    threadProgress = new Thread(counterThread);
                                    threadProgress.setName(CounterThread.class.toString());
                                    threadProgress.start();
                                }
                            }
                            try {
                                try {
                                    File xslFile = new File(fileInstance.getConversionScriptPath());

                                    File outputFile = new File(Utilities.TEMP_DIR + "temp_" + file.getName());
                                    outputFile.deleteOnExit();
                                    StringWriter xslMessages;
                                    HashMap<String, String> parameters = dataPreparationToolGUI.getParams();
                                    parameters.put("eadidmissing", eadid);
                                    CheckIsEadFile checkIsEadFile = new CheckIsEadFile(file);
                                    checkIsEadFile.run();
                                    if (checkIsEadFile.isEadRoot()) {
                                        File outputFile_temp = new File(
                                                Utilities.TEMP_DIR + ".temp_" + file.getName());
                                        TransformationTool.createTransformation(FileUtils.openInputStream(file),
                                                outputFile_temp, Utilities.BEFORE_XSL_FILE, null, true, true,
                                                null, true, null);
                                        xslMessages = TransformationTool.createTransformation(
                                                FileUtils.openInputStream(outputFile_temp), outputFile, xslFile,
                                                parameters, true, true, null, true, counterCLevelCall);
                                        outputFile_temp.delete();
                                    } else {
                                        xslMessages = TransformationTool.createTransformation(
                                                FileUtils.openInputStream(file), outputFile, xslFile,
                                                parameters, true, true, null, true, null);
                                    }
                                    fileInstance.setConversionErrors(xslMessages.toString());
                                    fileInstance
                                            .setCurrentLocation(Utilities.TEMP_DIR + "temp_" + file.getName());
                                    fileInstance.setConverted();
                                    fileInstance.setLastOperation(FileInstance.Operation.CONVERT);
                                    uniqueXslMessage = xslMessages.toString();
                                    if (xslMessages.toString().equals("")) {
                                        if (fileInstance.getConversionScriptName()
                                                .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) {
                                            fileInstance.setConversionErrors(
                                                    labels.getString("conversion.noExcludedElements"));
                                        } else {
                                            fileInstance.setConversionErrors(
                                                    labels.getString("conversion.finished"));
                                        }
                                    }

                                    if (!continueLoop) {
                                        break;
                                    }

                                } catch (Exception e) {
                                    fileInstance.setConversionErrors(labels.getString("conversionException")
                                            + "\r\n\r\n-------------\r\n" + e.getMessage());
                                    throw new Exception("Error when converting " + file.getName(), e);
                                }

                                if (threadProgress != null) {
                                    counterThread.stop();
                                    threadProgress.interrupt();
                                }
                                if (progressBar != null) {
                                    if (counterMax > 0) {
                                        progressBar.setValue(counterMax);
                                    }
                                    progressBar.setIndeterminate(true);
                                }

                            } catch (Exception e) {
                                LOG.error("Error when converting and validating", e);
                            } finally {
                                summaryWorking.stop();
                                threadRunner.interrupt();
                                dataPreparationToolGUI.getXmlEadListLabel().repaint();
                                dataPreparationToolGUI.getXmlEadList().repaint();
                                if (progressBar != null) {
                                    progressBar.setVisible(false);
                                }
                            }
                        }
                        if (numberOfFiles == 1) {
                            uniqueFileInstance = fileInstance;
                        }
                    }

                    if (type == VALIDATE || type == CONVERT_AND_VALIDATE) {

                        try {
                            try {
                                File fileToValidate = new File(fileInstance.getCurrentLocation());
                                InputStream is = FileUtils.openInputStream(fileToValidate);
                                dataPreparationToolGUI
                                        .setResultAreaText(labels.getString("validating") + " " + file.getName()
                                                + " (" + currentFileNumberBatch + "/" + numberOfFiles + ")");
                                XsdObject xsdObject = fileInstance.getValidationSchema();

                                List<SAXParseException> exceptions;
                                if (xsdObject.getName().equals(Xsd_enum.DTD_EAD_2002.getReadableName())) {
                                    exceptions = DocumentValidation.xmlValidationAgainstDtd(
                                            fileToValidate.getAbsolutePath(),
                                            Utilities.getUrlPathXsd(xsdObject));
                                } else {
                                    exceptions = DocumentValidation.xmlValidation(is,
                                            Utilities.getUrlPathXsd(xsdObject), xsdObject.isXsd11());
                                }
                                if (exceptions == null || exceptions.isEmpty()) {
                                    fileInstance.setValid(true);
                                    fileInstance.setValidationErrors(labels.getString("validationSuccess"));
                                    if (xsdObject.getFileType().equals(FileInstance.FileType.EAD)
                                            && xsdObject.getName().equals("apeEAD")) {
                                        XmlQualityCheckerCall xmlQualityCheckerCall = new XmlQualityCheckerCall();
                                        InputStream is2 = FileUtils
                                                .openInputStream(new File(fileInstance.getCurrentLocation()));
                                        TransformationTool.createTransformation(is2, null,
                                                Utilities.XML_QUALITY_FILE, null, true, true, null, false,
                                                xmlQualityCheckerCall);
                                        String xmlQualityStr = createXmlQualityString(xmlQualityCheckerCall);
                                        fileInstance.setValidationErrors(
                                                fileInstance.getValidationErrors() + xmlQualityStr);
                                        fileInstance.setXmlQualityErrors(
                                                createXmlQualityErrors(xmlQualityCheckerCall));
                                    }
                                } else {
                                    String errors = Utilities.stringFromList(exceptions);
                                    fileInstance.setValidationErrors(errors);
                                    fileInstance.setValid(false);
                                }
                                fileInstance.setLastOperation(FileInstance.Operation.VALIDATE);
                            } catch (Exception ex) {
                                fileInstance.setValid(false);
                                fileInstance.setValidationErrors(labels.getString("validationException")
                                        + "\r\n\r\n-------------\r\n" + ex.getMessage());
                                throw new Exception("Error when validating", ex);
                            }
                        } catch (Exception e) {
                            LOG.error("Error when validating", e);
                        } finally {
                            summaryWorking.stop();
                            threadRunner.interrupt();
                            dataPreparationToolGUI.getXmlEadListLabel().repaint();
                            dataPreparationToolGUI.getXmlEadList().repaint();
                            if (progressBar != null) {
                                progressBar.setVisible(false);
                            }
                        }
                        if (numberOfFiles == 1) {
                            uniqueFileInstance = fileInstance;
                        }
                    }
                }
            }
            Toolkit.getDefaultToolkit().beep();
            if (progressFrame != null) {
                try {
                    progressFrame.stop();
                } catch (Exception e) {
                    LOG.error("Error when stopping the progress bar", e);
                }
            }
            dataPreparationToolGUI.getFinalAct().run();
            if (numberOfFiles > 1) {
                dataPreparationToolGUI.getXmlEadList().clearSelection();
            } else if (uniqueFileInstance != null) {
                if (type != VALIDATE) {
                    dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                            .setConversionErrorText(replaceGtAndLt(uniqueFileInstance.getConversionErrors()));
                    if (uniqueXslMessage.equals("")) {
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_GREEN_COLOR);
                    } else {
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_RED_COLOR);
                    }
                }
                if (type != CONVERT) {
                    dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                            .setValidationErrorText(uniqueFileInstance.getValidationErrors());
                    if (uniqueFileInstance.isValid()) {
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_GREEN_COLOR);
                        if (uniqueFileInstance.getValidationSchema()
                                .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))) {
                            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionEdmBtn();
                            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn();
                        } else if (uniqueFileInstance.getValidationSchema()
                                .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))
                                || uniqueFileInstance.getValidationSchema()
                                        .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath()))
                                || uniqueFileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) {
                            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionBtn();
                            // dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn();
                        }
                    } else {
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_RED_COLOR);
                        if (uniqueFileInstance.getValidationSchema()
                                .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))
                                || uniqueFileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))
                                || uniqueFileInstance.getValidationSchema()
                                        .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath()))
                                || uniqueFileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_EAC_SCHEMA.getPath()))
                                || uniqueFileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) {
                            dataPreparationToolGUI.enableConversionBtns();
                            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                    .enableConvertAndValidateBtn();
                        }
                    }
                }
                dataPreparationToolGUI.enableMessageReportBtns();
            }
            if (continueLoop) {
                dataPreparationToolGUI.setResultAreaText(labels.getString("finished"));
            } else {
                dataPreparationToolGUI.setResultAreaText(labels.getString("aborted"));
            }
            dataPreparationToolGUI.enableSaveBtn();
            if (type == CONVERT) {
                dataPreparationToolGUI.enableValidationBtns();
            }
            dataPreparationToolGUI.enableRadioButtons();
            dataPreparationToolGUI.enableEditionTab();
        }
    }).start();
}

From source file:org.compass.core.test.concurrency.singlewritermultireader.AbstractSingleWriterMultiReaderTests.java

public void testSingleWriterMultiReader() {
    Thread writerThread = new Thread(new Runnable() {
        public void run() {
            CompassTemplate template = new CompassTemplate(getCompass());
            try {
                for (long count = 0; count < getNumberOfObjects(); count++) {
                    A a = new A();
                    a.id = count;//from w  w  w.  j  ava 2 s  .  c  o m
                    a.data1 = "" + count;
                    template.save(a);
                    lastId.incrementAndGet();
                }
            } catch (Exception e) {
                error = true;
                logger.error("WRITER THREAD FAILED", e);
            }
            writerDone = true;
        }
    });
    writerThread.setName("WRITER");

    Thread[] readerThreads = new Thread[getNumberOfReaders()];
    for (int i = 0; i < readerThreads.length; i++) {
        readerThreads[i] = new Thread(new Runnable() {
            public void run() {
                CompassTemplate template = new CompassTemplate(getCompass());
                while (!writerDone) {
                    try {
                        for (long i = 0; i < lastId.get(); i++) {
                            A a = template.get(A.class, i);
                            if (a == null) {
                                error = true;
                                logger.error("FAILED TO READ ID [" + i + "]");
                            }
                        }
                    } catch (Exception e) {
                        error = true;
                        logger.error("READER THREAD FAILED", e);
                    }
                }
            }
        });
        readerThreads[i].setName("READER[" + i + "]");
    }
    writerThread.start();
    for (Thread readerThread : readerThreads) {
        readerThread.start();
    }

    try {
        writerThread.join();
    } catch (InterruptedException e) {
        logger.error("Failed to join on writer thread, interrupted", e);
    }
    for (Thread readerThread : readerThreads) {
        try {
            readerThread.join();
        } catch (InterruptedException e) {
            logger.error("Failed to join on reader thread, interrupted", e);
        }
    }

    if (error) {
        fail("Single writer multi writer test failed, see logs...");
    }
}

From source file:org.apache.hadoop.fs.azure.BlockBlobAppendStream.java

/**
 * Helper method that starts an Append Lease renewer thread and the
 * thread pool./*from  w w  w  . ja  v  a  2 s . c  o  m*/
 */
public synchronized void initialize() {

    if (initialized) {
        return;
    }
    /*
     * Start the thread for  Append lease renewer.
     */
    Thread appendLeaseRenewer = new Thread(new AppendRenewer());
    appendLeaseRenewer.setDaemon(true);
    appendLeaseRenewer.setName(String.format("%s-AppendLeaseRenewer", key));
    appendLeaseRenewer.start();

    /*
     * Parameters to ThreadPoolExecutor:
     * corePoolSize : the number of threads to keep in the pool, even if they are idle,
     *                unless allowCoreThreadTimeOut is set
     * maximumPoolSize : the maximum number of threads to allow in the pool
     * keepAliveTime - when the number of threads is greater than the core,
     *                 this is the maximum time that excess idle threads will
     *                 wait for new tasks before terminating.
     * unit - the time unit for the keepAliveTime argument
     * workQueue - the queue to use for holding tasks before they are executed
     *  This queue will hold only the Runnable tasks submitted by the execute method.
     */
    this.ioThreadPool = new ThreadPoolExecutor(4, 4, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
            new UploaderThreadFactory());

    initialized = true;
}

From source file:com.zimbra.cs.mailclient.imap.ImapConnection.java

private ImapResponse sendIdle(ImapRequest req) {
    request = req;//w ww . j a  va  2  s .c om
    try {
        req.write(getImapOutputStream());
        ImapResponse res = waitForResponse();
        if (res.isTagged()) {
            return res;
        }
        assert res.isContinuation();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                idleHandler();
            }
        });
        t.setName("IMAP IDLE thread");
        t.setDaemon(true);
        t.start();
    } catch (IOException e) {
        request = null;
    }
    return null;
}

From source file:org.apache.hadoop.yarn.server.MiniYARNClusterSplice.java

private synchronized void startResourceManager(final int index) {
    try {//from   w  w w  .  j a  v  a2  s  .co m
        Thread rmThread = new Thread() {
            public void run() {
                resourceManagers[index].start();
            }
        };
        rmThread.setName("RM-" + index);
        rmThread.start();
        int waitCount = 0;
        while (resourceManagers[index].getServiceState() == STATE.INITED && waitCount++ < 60) {
            LOG.info("Waiting for RM to start...");
            Thread.sleep(1500);
        }
        if (resourceManagers[index].getServiceState() != STATE.STARTED) {
            // RM could have failed.
            throw new IOException("ResourceManager failed to start. Final state is "
                    + resourceManagers[index].getServiceState());
        }
    } catch (Throwable t) {
        throw new YarnRuntimeException(t);
    }
    LOG.info("MiniYARN ResourceManager address: " + getConfig().get(YarnConfiguration.RM_ADDRESS));
    LOG.info("MiniYARN ResourceManager web address: " + WebAppUtils.getRMWebAppURLWithoutScheme(getConfig()));
}

From source file:uk.co.tekkies.readings.activity.ReadingsActivity.java

private void showNewsToast() {
    final String versionName = getVersionName();
    Thread thread = new Thread(new Runnable() {
        @Override/*  w ww .j  a v  a 2 s  .  c  o m*/
        public void run() {
            String summary = backgroundDownloadNewsToast(versionName);
            if (summary != null && summary != "") {
                Message message = Message.obtain(newsToastHandler, 0, summary);
                newsToastHandler.sendMessage(message);
            }
        }
    });
    thread.setName("Download news toast");
    thread.start();
}

From source file:bamboo.trove.rule.RuleChangeUpdateManager.java

private void startProcessing() {
    if (!running && !stopping) {
        log.info("Starting...");
        running = true;/*  w ww . j  av  a  2  s  .c o m*/
        Thread me = new Thread(this);
        me.setName(getName());
        me.start();
    }
}

From source file:org.apache.pulsar.io.twitter.TwitterFireHose.java

private void startThread(TwitterFireHoseConfig config) {

    BasicClient client = new ClientBuilder().name(config.getClientName()).hosts(config.getClientHosts())
            .endpoint(getEndpoint(config)).authentication(getAuthentication(config))
            .processor(new HosebirdMessageProcessor() {
                public DelimitedStreamReader reader;

                @Override/*w  ww  .ja  v  a 2s .c om*/
                public void setup(InputStream input) {
                    reader = new DelimitedStreamReader(input, Constants.DEFAULT_CHARSET,
                            config.getClientBufferSize());
                }

                @Override
                public boolean process() throws IOException, InterruptedException {
                    String tweetStr = reader.readLine();
                    try {
                        TweetData tweet = mapper.readValue(tweetStr, TweetData.class);
                        // We don't really care if the record succeeds or not.
                        // However might be in the future to count failures
                        // TODO:- Figure out the metrics story for connectors
                        consume(new TwitterRecord(tweet, config.getGuestimateTweetTime()));
                    } catch (Exception e) {
                        LOG.error("Exception thrown: {}", e);
                    }
                    return true;
                }
            }).build();

    Thread runnerThread = new Thread(() -> {
        LOG.info("Started the Twitter FireHose Runner Thread");
        client.connect();
        LOG.info("Twitter Streaming API connection established successfully");

        // just wait now
        try {
            synchronized (waitObject) {
                waitObject.wait();
            }
        } catch (Exception e) {
            LOG.info("Got a exception in waitObject");
        }
        LOG.debug("Closing Twitter Streaming API connection");
        client.stop();
        LOG.info("Twitter Streaming API connection closed");
        LOG.info("Twitter FireHose Runner Thread ending");
    });
    runnerThread.setName("TwitterFireHoseRunner");
    runnerThread.start();
}

From source file:org.apache.flume.channel.recoverable.memory.TestRecoverableMemoryChannel.java

@Test
public void testRollbackWithSink() throws Exception {
    final NullSink nullSink = new NullSink();
    Context ctx = new Context();
    ctx.put("batchSize", "1");
    nullSink.configure(ctx);//from w  ww .  j ava2 s  . co  m
    nullSink.setChannel(channel);
    final int numItems = 99;
    Thread t = new Thread() {
        @Override
        public void run() {
            int count = 0;
            while (count++ < numItems) {
                try {
                    nullSink.process();
                    Thread.sleep(1);
                } catch (EventDeliveryException e) {
                    break;
                } catch (Exception e) {
                    Throwables.propagate(e);
                }
            }
        }
    };
    t.setDaemon(true);
    t.setName("NullSink");
    t.start();

    putEvents(channel, "rollback", 10, 100);

    Transaction transaction;
    // put an item we will rollback
    transaction = channel.getTransaction();
    transaction.begin();
    channel.put(EventBuilder.withBody("this is going to be rolledback".getBytes(Charsets.UTF_8)));
    transaction.rollback();
    transaction.close();

    while (t.isAlive()) {
        Thread.sleep(1);
    }

    // simulate crash
    channel.stop();
    channel = createFileChannel();

    // get the item which was not rolled back
    transaction = channel.getTransaction();
    transaction.begin();
    Event event = channel.take();
    transaction.commit();
    transaction.close();
    Assert.assertNotNull(event);
    Assert.assertEquals("rollback-90-9", new String(event.getBody(), Charsets.UTF_8));
}